Programmatic API of http.server
suggest changePython 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents