typestar

A minimal HTTP server in Python

Serving one request with http.server's base handler.

from http.server import BaseHTTPRequestHandler, HTTPServer


class Hello(BaseHTTPRequestHandler):
    def do_GET(self):
        body = f"you asked for {self.path}".encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


server = HTTPServer(("127.0.0.1", 8000), Hello)
server.handle_request()  # serve exactly one request, then fall through

How it works

  1. do_GET handles every GET request.
  2. send_response and headers precede the body.
  3. wfile.write sends the response bytes.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
446
Tokens
102
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 3 of 4 in Web, step 12 of 41 in Domain tools.

← Previous Next →