Python Glossary Русский

Python 3.0+http.serverterm

http.server.SimpleHTTPRequestHandler

request handlers

A ready-made handler that serves files and directory listings over GET and HEAD; the basis of python -m http.server.

Syntax

SimpleHTTPRequestHandler(request, client_address, server, directory=None)

By default it serves the current working directory, not the script's directory; pick another one with functools.partial(SimpleHTTPRequestHandler, directory=...). Everything is served, including .git and .env, with no authentication — it is a development tool, not production. Paths with .. are normalised and never escape the root. POST is not supported — the answer is 501.

Examples

import io, os, functools
from http.server import SimpleHTTPRequestHandler
class Files(SimpleHTTPRequestHandler):
    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[:5])
os.makedirs('public', exist_ok=True)
with open('public/hello.txt', 'w') as f:
    f.write('hello')
with open('secret.txt', 'w') as f:  # лежит выше корня раздачи
    f.write('token')
handler = functools.partial(Files, directory='public')
handler(b'GET /hello.txt HTTP/1.1\r\n\r\n', ('127.0.0.1', 5000), None)
# → HTTP/1.0 200 OK b'hello'
handler(b'GET /../secret.txt HTTP/1.1\r\n\r\n', ('127.0.0.1', 5000), None)
# → HTTP/1.0 404 File not found

See also

Open in the full glossarydocs.python.orgReport an inaccuracy