A webserver in Python can be setup in two ways. Python supports a webserver out of the box. You can start a web server with a one liner.

But you can also create a custom web server which has unique functionality. In this article you’ll learn how to do that.

The web server in this example can be accessed on your local network only. This can either be localhost or another network host. You could serve it cross location with a vpn.

Related course: Complete Python Programming Course & Exercises

Example

Builtin webserver

To start a webserver run the command below:

1
python3 -m http.server

That will open a webserver on port 8080. You can then open your browser at http://127.0.0.1:8080/

The webserver is also accessible over the network using your 192.168.-.- address.

This is a default server that you can use to download files from the machine.

Web server

Run the code below to start a custom web server. To create a custom web server, we need to use the HTTP protocol.

By design the http protocol has a “get” request which returns a file on the server. If the file is found it will return 200.

The server will start at port 8080 and accept default web browser requests.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))

if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))

try:
webServer.serve_forever()
except KeyboardInterrupt:
pass

webServer.server_close()
print("Server stopped.")

If you open an url like http://127.0.0.1/example the method do_GET() is called. We send the webpage manually in this method.

web server in python 3

The variable self.path returns the web browser url requested. In this case it would be /example

Download examples and exercises