Python is a batteries-included kind of language, and so of course it comes with an HTTP server module. Today I wanted to have something small running on my computer without dependencies to test a server-side example, so I looked into how to create a minimal server using python built-ins. This is what I ended up with:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from http.server import *

class Resp(BaseHTTPRequestHandler):
    def do_GET(self):
        self.wfile.write(b"""HTTP/1.1 200 OK
Content-Type: text/html
Location: localhost:8000

<html>
<head><title>Hello, world</title></head>
<body>Minimal page written in python</body>
</html>
""")


def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

run(HTTPServer, Resp)

First of all, since this is just for trying it out, I imported everything from http.server. Never do this in normal code. We use HTTPServer and initialise it with the port we want to serve to and a handler class Resp that we subclass from BaseHTTPRequestHandler.

We add a do_GET method to our class, making it reply to all GET requests with that module. I don’t know how they implemented this, but it doesn’t sound like it would be pretty.

The request handler class has an instance variable wfile which is where we’re supposed to write our response. The response is supposed to be a bytestring, hence the b""", and it needs to be valid HTTP so that whatever tool we use to read it does not choke on it. Write the headers you want (including response code) and then the body.

the response open in emacs saying "minimal page written in python"

There’s also a threading server you can use if you want concurrency, I’ve never tried it.

Extra info because I’m nice

Inside any directory with web files, you can run

python3 -m http.server 8000 # use the port you want

to serve the files to your browser. This is useful to get around restrictions that plain html files have when opened.