Programmatic API of http.server

suggest change

Python 3 moved the Python 2 SimpleHTTPServer, BaseHTTPServer, and SocketServer modules into http.server and socketserver.

The command python -m http.server 9000 creates an HTTP server using SimpleHTTPRequestHandler and listens on all interfaces. A programmatic server with the same handler, bound only to the loopback interface, is:

from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer

server = ThreadingHTTPServer(("127.0.0.1", 9000), SimpleHTTPRequestHandler)
try:
    server.serve_forever()
except KeyboardInterrupt:
    pass
finally:
    server.server_close()

HTTPServer and ThreadingHTTPServer (both in http.server) extend this socketserver hierarchy:

BaseServer
└── TCPServer
    ├── HTTPServer
    │   └── ThreadingHTTPServer
    └── UnixStreamServer (Unix only)

Prefer the context-manager form shown on the “Serving files” page when possible, because it closes the listening socket automatically.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents