Python http.server From Zero: One Line to Serve, Three Real Traps
http.server from zero: a 24-line transcript on Python 3.12.3 serves a directory on port 18742 and shows three real traps: the default bind is 0.0.0.0 so the whole LAN can reach it, HTTPServer takes 4.0s for two 2-second requests while ThreadingHTTPServer takes 2.0s, and a symlink serves a file from outside the directory. On 3.12 the CLI has no TLS option at all.

Every Python user runs into the same situation sooner or later: a freshly written static page, or a pile of files just copied from somewhere, that you want to see in a browser right now. Installing nginx is overkill; writing a server is too much work — and the standard library already has the answer: http.server, one command to turn a directory into a website. This guide starts from zero and works through 22 lines of tested output on Python 3.12.3, covering the command-line use, the library use, and three real traps: the default bind is 0.0.0.0, so anyone on the same LAN can reach it; HTTPServer handles one request at a time, so a single slow request blocks everybody; and the documentation says up front that it is not recommended for production and only implements basic security checks — and on 3.12 it does not even have a TLS option.
The demo environment first: Python 3.12.3, standard library only, demo script demo275_httpserver.py, 22 lines of output, ports 18742 to 18745, all bound to 127.0.0.1. The work directory is wiped and rebuilt on every run and holds four things: index.html (containing hello-http-server), hello.txt, secret-note.txt (containing pretend this is private, there to prove that any file in the directory gets served), and a files/ subdirectory holding note.txt. There is also an escape.txt, a symlink pointing outside the work directory — the trap in §5 lives there. One normalisation to explain: the command-line server logs every request to stderr with a timestamp, so the script sends that to the void to keep reruns byte-identical; and the two timing lines (4.0 seconds and 2.0 seconds) wobble by a few tenths of a second per run, so the validator treats those two lines specially — the verdict words BLOCKED and CONCURRENT are decided by a 3.5-second threshold and do not wobble.
§0 The command line: serve a directory in one line
The most-used form is a single command: python3 -m http.server 18742 --bind 127.0.0.1 --directory <workdir>. With no port it defaults to 8000; --bind picks the address; --directory picks the directory, defaulting to the current one. Once the demo server was up, urllib fired six requests at it: GET / returned 200 with body hello-http-server — because the directory holds an index.html, which is served as the directory's home page; GET /hello.txt returned 200 with body hello text file; GET /files/ returned 200, and the directory listing it returned really does contain note.txt; GET /missing.txt returned 404; and the Server response header reads SimpleHTTP/0.6 Python/3.12.3.
Behind those six requests is the fixed flow of SimpleHTTPRequestHandler.do_GET, spelled out in the documentation: map the request path to a file under the directory; if it maps to a directory, look for index.html or index.htm (the list of home-page names is configurable since 3.12) — return the file if found, otherwise generate a directory listing; if it maps to a file, open it and return it with a Content-Type guessed from the extension, a Content-Length with the file size, and a Last-Modified with the modification time; if the file cannot be opened (because it does not exist, for example) return 404, File not found. One detail the demo verified along the way: a request with If-Modified-Since: 2031 returns 304 Not Modified, because the file genuinely has not changed since then — that is how browsers cache, instead of downloading everything every time.
The Content-Type of a response is guessed from the file extension: .html becomes text/html, and a file with no extension is served as application/octet-stream — both verified in the demo environment. The guess comes from the extensions_map table plus the system's own MIME database, so the same file can occasionally be guessed differently on different machines; when a browser treats your file as a download instead of displaying it, check the Content-Type in the response headers first. do_HEAD sends the same headers as do_GET but no body — cheaper than GET for checking whether a link works or a file exists. The directory listing itself is generated on the spot by list_directory using os.listdir: there is no cache, so a file added to the directory shows up in the very next request.
The home-page rule is worth a sentence too: if a directory holds an index.html or an index.htm, requesting that directory returns the file directly instead of generating a listing — the documentation calls this default index_pages, configurable since 3.12. Subdirectories work the same way: if /files/ held an index.html, requesting /files/ would return it instead of a listing. In the demo the root holds an index.html and files/ does not, so GET / returns file contents while GET /files/ returns a listing — one rule, two outcomes.
Once the server is up, the terminal prints every request live, in a fixed format verified separately from the demo: one line at startup, Serving HTTP on 127.0.0.1 port 18748 (http://127.0.0.1:18748/) ...; then one line per request, 127.0.0.1 - - [30/Nov/2026 07:26:00] "GET / HTTP/1.1" 200 - — client address first, the request line with a timestamp in the middle, the status code at the end; and a 404 adds an extra line, code 404, message File not found. All of it goes to stderr, which is why the demo script sends it to the void — the timestamps would break byte-identical reruns. In everyday use, leave it on: who took which file and when is entirely in those lines.
§1 Trap 1: the default bind is 0.0.0.0 — everyone on the LAN can reach it
The first trap is set before the server even starts. The demo asked two server objects for their own bind address: HTTPServer(('', 18743)) reports server_address as ('0.0.0.0', 18743), while HTTPServer(('127.0.0.1', 18743)) reports ('127.0.0.1', 18743). The documentation says it plainly in the --bind section: "By default, the server binds itself to all interfaces." In other words, a bare python3 -m http.server 8000 is reachable not only from your own machine but from any device on the same Wi-Fi, and anyone who can reach your machine — office network, café Wi-Fi, shared flat, all the same.
Put that together with the two 200s from §0 and the picture is complete: GET /secret-note.txt returned 200 with body pretend this is private — calling a file "secret" changes nothing; if it sits in the directory, it gets served. And GET /escape.txt also returned 200, with body outside-secret — that file is not in the work directory at all, it lives in /tmp, and the work directory holds only a symlink pointing at it. The documentation's "Security considerations" section says so explicitly: SimpleHTTPRequestHandler will follow symbolic links, which makes it possible for files outside of the specified directory to be served. So the correct habit has two halves: serve only a directory prepared for the purpose (never start it in $HOME), and always write --bind 127.0.0.1 explicitly. Either half on its own is not enough.
Incidentally, --bind also accepts IPv6 addresses (since 3.8): --bind ::1 binds only the machine's IPv6 loopback, the counterpart of 127.0.0.1. For everyday use, remember two rules: with no --bind, every interface can reach the server; with --bind 127.0.0.1, only the local machine can — and the two server_address lines in the demo are the direct evidence for both.
Once the server is up, how do you confirm what it actually bound to? The quickest way is lsof from the previous guide: lsof -i :18742 lists the process listening on that port and its address, and whether it bound 127.0.0.1 or *:18742 (all interfaces) is visible at a glance. When you suspect the server never came up, check lsof -i :port first and look at the server's own log second — very often the problem is not that the server failed to start, but that it started on an address you did not expect, or the port was already taken by another process.
§2 The module's structure: four classes, each with one job
The http.server module is small; its core is four classes, and once you see the split of responsibilities everything else follows. HTTPServer is the server itself: it listens on the port, accepts connections, and hands requests to a handler. ThreadingHTTPServer is identical except that it handles each request in its own thread (added in 3.7). BaseHTTPRequestHandler is the base class for handlers; on its own it cannot answer any real request — a subclass must implement do_GET, do_POST, and friends. SimpleHTTPRequestHandler is the ready-made subclass implementing do_GET and do_HEAD — the static file server from the §0 demo. The documentation's standard example is these few lines:
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
Note the ("", PORT) in that example — an empty string is the bind-everything default from §1, so swap it for ("127.0.0.1", PORT) in your own code. A few other knobs are worth knowing: the directory parameter of SimpleHTTPRequestHandler (added in 3.7) picks the served directory without needing a chdir; index_pages (added in 3.12) changes the home-page filenames; and --protocol (added in 3.11) picks the HTTP version, which defaults to HTTP/1.0.
Once the server is running, two methods control it: serve_forever() runs until another thread calls shutdown() — that is how the demo script stops its servers. One default is easy to overlook: HTTPServer.allow_reuse_address = 1 (verified by inspection), which means the server can bind the same port again immediately after stopping, with no Address already in use error — a real time-saver when you are restarting a server over and over in demos and tests. If you want to handle exactly one request and return, there is handle_request(): one call, one connection — the handiest shape for a single-request test.
The inheritance is worth one sentence too: HTTPServer is a subclass of socketserver.TCPServer that adds exactly two things — it stores the address as the instance variables server_name and server_port, reachable from a handler through self.server; everything else, listening, accepting connections, dispatching requests, is TCPServer's existing machinery. So if you need to know which port the server itself bound to inside a do_GET, read self.server.server_port — no guessing. That also explains ThreadingHTTPServer: it is HTTPServer plus ThreadingMixIn, opening one extra thread per request at dispatch time and otherwise identical.
§3 Trap 2: HTTPServer handles one request at a time
The second trap is about performance, and it is hard to notice in normal use. The demo wrote a custom handler where the /slow path sleeps two seconds before answering slow-ok, then fired two /slow requests at the same time from two threads and measured the total. Result: HTTPServer took 4.0 seconds, verdict BLOCKED; ThreadingHTTPServer took 2.0 seconds, verdict CONCURRENT. Two requests at two seconds each: four seconds in sequence, two seconds in parallel — the numbers say it all. HTTPServer handles one request at a time; while the first is still being processed, the second can only wait outside.
The documentation has a blunt explanation for why the threaded version exists: it is "useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely." In plain language: browsers routinely open a few empty connections in advance to be fast, and with HTTPServer a single empty connection can block everybody else. So the rule is simple: whenever a browser will touch the server, use ThreadingHTTPServer, not HTTPServer. Incidentally, ThreadingHTTPServer's threads are daemon threads (daemon_threads = True, verified by inspection), so they never hold the process open when the main thread exits — handy when writing demos and tests.
But the threaded version is not free either: one thread per request, no thread pool, no upper limit — more requests means more threads, and memory and switching overhead grow with them. For local debugging with a few people looking at once, that is completely fine; for carrying real traffic, threads and file descriptors run out before bandwidth does. One more detail follows from the daemon threads: when the main thread exits, requests still being processed are dropped outright — fine for a demo, but a real service cannot rely on daemon threads to guarantee that a request finishes. That is another reason it is a debugging tool only: its concurrency model is "as many as arrive", with no backpressure and no rate limiting.
§4 Writing your own handler: do_GET and the response format
A custom handler is simpler than it looks; the demo's SlowHandler is a complete example. Subclass BaseHTTPRequestHandler, implement a do_GET, branch on self.path, call self.send_response(200) for the status line, self.send_header("Content-Type", "text/plain") and self.send_header("Content-Length", ...) for the headers, self.end_headers() to finish the header block, and finally write the body into self.wfile. Request methods map one-to-one onto handler functions: a GET calls do_GET, a POST calls do_POST, and even a made-up SPAM method would call do_SPAM — the name is assembled exactly that way.
Two formatting rules come from the documentation, and getting them wrong makes browsers behave strangely. First, protocol_version defaults to HTTP/1.0; if you switch it to HTTP/1.1, every response must carry an accurate Content-Length, because 1.1 connections stay open by default and the browser uses that length to know where the body ends — get it wrong and it waits forever. Second, send_response adds Server and Date headers automatically, while send_header only buffers headers — nothing is sent until end_headers is called, so getting the order wrong leaves the response stuck. The demo also overrides log_message with an empty function: the default implementation logs every request to stderr, and turning it off keeps demo and test output clean.
do_POST follows the same pattern as do_GET, and the demo runs it too: POST /echo returns 200 with the body echoed back verbatim, hello-post. The rule for reading a request body is to take Content-Length first, then read exactly that many bytes from self.rfile — no more, no guessing. Change that skeleton slightly and you have a working webhook receiver: read the body in do_POST, print it or store it, and answer 200. One small warning: self.path holds the full path including the query string (for example /search?q=abc), so split path from query with urllib.parse.urlparse before comparing — otherwise self.path == "/search" is never true.
The handler carries more than self.path: self.client_address is the peer's (IP, port), self.command is the request method (GET, POST), self.headers holds the parsed request headers, self.requestline is the raw request line, self.rfile and self.wfile are the read and write streams, and self.server is the server object itself. One more detail: address_string() returns only the IP, with no reverse DNS lookup — the documentation says it has worked that way since 3.3, to avoid the lookup delay. Those ready-made attributes are enough for access logging and simple rate limiting, with no need to parse the raw message yourself.
§5 Trap 3: no auth, no TLS — local debugging only
The third trap is about what the tool is for, and the documentation states it at the top: http.server is not recommended for production; it only implements basic security checks. That is not politeness — the demo supplies three pieces of evidence. First, there is no authentication at all: whoever connects gets the files, as secret-note.txt in §1 proves. Second, on the demo's Python 3.12.3 the command line has no TLS option at all: --tls-cert and --tls-key were added in 3.14, and the HTTPSServer class arrived in 3.14 too — on 3.12 it is plain HTTP, so passwords, tokens, and cookies travel in clear text. Third, the documentation says send_header and send_response_only assume sanitised input and do no validation such as rejecting CRLF sequences, so untrusted input can lead to HTTP header injection. Add the three together and there is only one conclusion: it is a local debugging tool, not a server.
Two more information leaks are worth handling while you are here. First, the Server response header: every response in the demo carries SimpleHTTP/0.6 Python/3.12.3, which tells every visitor the exact Python version — the documentation notes that the server_version class attribute can be overridden, so change it if you would rather not advertise. Second, the request log: before 3.12, control characters sent by a remote client went into the stderr log verbatim and could inject control codes into your terminal; since 3.12 those characters are scrubbed. The demo environment is 3.12.3, so this is already fixed there — but if you run python3 -m http.server on an older Python, treat odd characters in the log with suspicion.
§6 When to use it, and when not to
Pulling the previous five sections together into one decision table. There are four good uses for http.server. First, local preview: a freshly written static page or a fresh build output that you want to see in a browser — one command, then Ctrl+C when done. Second, passing a file around: an installer or a log file to a colleague on a trusted LAN — but think first about whether to bind 127.0.0.1 or a LAN address, and shut it down when the transfer is done; never leave it running overnight. Third, as a test target: the do_POST skeleton from §4 becomes a webhook receiver or a landing spot for a third-party callback with a few changes — get the flow working against it first, then connect the real service. Fourth, teaching: when you are explaining how HTTP requests and responses work, leave the default log_message on and every line on the terminal is one real request — method, path, and status code, right there — and paired with curl -v showing the request and response lines, it beats any diagram.
And three hard no's. First, serving the public: no authentication, no TLS (not even an option on 3.12), no rate limiting — putting it on the public internet is walking around naked. Second, anything that needs HTTPS or needs to hide its version: the command line cannot do TLS on 3.12, and the Server header advertises the version by default. Third, heavy concurrency or long-lived connections: the threaded version has no thread pool and loses control as requests pile up, while the single-threaded version lets one slow request block everyone — neither is built to carry traffic. The rule of thumb is one sentence: if anyone would be hurt by this server going away, do not use http.server; if it is only you taking a quick look locally, it is the handiest tool there is.
Finally, three questions to ask yourself before every launch, before you press Enter: one, is it bound to 127.0.0.1 — with no --bind, that is every interface; two, is there anything in the directory that should not be shared — including files hiding behind a symlink, as escape.txt in §1 showed; three, will you shut it down when done — Ctrl+C is enough, just do not leave it running in the background overnight. If you can answer all three, press Enter; if any one is unclear, tidy the directory first and then start it.
Cheat sheet
python3 -m http.server 8000 # default port 8000, binds all interfaces
python3 -m http.server 18742 --bind 127.0.0.1 # localhost only
python3 -m http.server --directory /tmp/site # serve a chosen directory
python3 -m http.server --protocol HTTP/1.1 # HTTP/1.1 (3.11+)
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
httpd = ThreadingHTTPServer(("127.0.0.1", 8000), SimpleHTTPRequestHandler)
httpd.serve_forever() # threaded version — use this for browsers
Boundary: how this differs from neighbouring guides on the site
The site already has vibe-project-python-basics-stdlib-tour-guide, a tour of the standard library that passes many modules in one article — this one takes a single module out of the tour and goes deep, from the command line through custom handlers to three traps; the depth is different. There is also vibe-project-python-basics-file-io-guide, about a program reading and writing local files itself; this one is about handing files to other people over HTTP — local file access versus serving over a network. And the site has vibe-project-webhooks-integration-guide, about consuming other people's webhooks — the custom handler in §4 here is exactly what you would use to build a local webhook receiver for testing, so the two are complementary: one is "how to consume", the other "how to build a target to verify against".

Comments (0)
Sources
Related articles
cron is the scheduling daemon that has run on Linux for decades: write a crontab file saying 'run this command at this time', and it handles the rest. This guide runs everything for real on Debian cron 3.0pl1-162 — installing a job, waiting one minute for the trigger, verifying the log, removing the job — plus special strings, five classic mistakes, and a real 3 a.m. log-archiving job.
ping does exactly one thing: send an ICMP echo request, wait for the echo reply, and report the round-trip time and packet loss. This guide runs every command for real on iputils ping 20240117 — packet count, interval, quiet mode, packet size, timestamps, IPv4 vs IPv6, the three failure modes, exit codes 0/1/2 — with output pasted verbatim.
cut does one thing: split each line into fields on a delimiter and output the fields you ask for. This guide runs every command for real on GNU coreutils 9.4 — field lists and ranges, CSV and output delimiters, character slicing, --complement, the -s rule for lines without a delimiter, log-column statistics, and the quoted-comma limit — with the output pasted verbatim.