Chapter 4. Web Servers
This chapter will first extend our experience with writing basic TCP
servers to the construction of basic HTTP servers. With that context and
understanding of the HTTP protocol in hand, we’ll then abandon the low-level
API in favor of the high-level twisted.web
APIs used for constructing sophisticated web servers.
Note
Twisted Web is the Twisted subproject focusing on HTTP communication. It has robust HTTP 1.1 and HTTPS client and server implementations, proxy support, WSGI integration, basic HTML templating, and more.
Responding to HTTP Requests: A Low-Level Review
The HyperText Transfer Protocol (HTTP) is a request/response application-layer protocol, where requests are initiated by a client to a server, which responds with the requested resource. It is text-based and newline-delimited, and thus easy for humans to read.
To experiment with the HTTP protocol we’ll create a subclass of protocol.Protocol, the same class we used to build our echo servers and clients in
Chapter 2. Our protocol will know how to accept a connection,
process the request, and send back an HTTP-formatted response.
This section is intended as both a glimpse under the hood and a
refresher on the HTTP protocol. When building real web servers, you’ll
almost certainly use the higher-level twisted.web APIs Twisted provides. If you’d
prefer to skip to that content, head over to Handling GET Requests.
The Structure of an HTTP Request
Every HTTP request starts with a single line containing the HTTP ...