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
do_GEThandles every GET request.send_responseand headers precede the body.wfile.writesends the response bytes.
Keywords and builtins used here
Helloclassdefdo_GETlenselfstr
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.
Step 3 of 4 in Web, step 12 of 41 in Domain tools.