Python 3.0+http.serverterm
http.server.BaseHTTPRequestHandler
request handlers
The base class of an HTTP request handler: it parses the request line and headers and calls your do_GET, do_POST and so on.
Syntax
class Handler(BaseHTTPRequestHandler):
def do_GET(self): ...
A new object is created for every request, so state cannot be kept on self between requests — put it on self.server. No do_<METHOD> method means the client gets 501. The order is mandatory: send_response(), send_header(), end_headers() — until end_headers() the headers sit in a buffer; wfile takes bytes. Read the request body for exactly Content-Length bytes: rfile.read() without a size waits for the connection to close and hangs. protocol_version defaults to 'HTTP/1.0'.
Examples
import io
from http.server import BaseHTTPRequestHandler
class Hello(BaseHTTPRequestHandler):
def setup(self): # вместо сокета — байты в памяти
self.rfile = io.BytesIO(self.request)
self.wfile = io.BytesIO()
def log_message(self, format, *args):
pass
def finish(self):
head, _, body = self.wfile.getvalue().partition(b'\r\n\r\n')
print(head.split(b'\r\n')[0].decode(), body[:20])
def do_GET(self):
body = f'path={self.path}'.encode()
self.send_response(200)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
Hello(b'GET /hi?x=1 HTTP/1.1\r\n\r\n', ('127.0.0.1', 5000), None)
# → HTTP/1.0 200 OK b'path=/hi?x=1'
Hello(b'POST /hi HTTP/1.1\r\n\r\n', ('127.0.0.1', 5000), None)
# → HTTP/1.0 501 Unsupported method ('POST')
See also
Open in the full glossarydocs.python.orgReport an inaccuracy