Foundations of Python Network Programming

(WallPaper) #1
169

Chapter 10

HTTP Servers


How can a Python program run as a server responding to HTTP requests? In Chapter 7, you learned several basic
socket and concurrency patterns for writing a TCP-based network server. With HTTP, it is unlikely that you will ever
need to write anything that low-level because the protocol’s popularity has resulted in off-the-shelf solutions for all of
the major server patterns that you might need.
While this chapter will focus on third-party tools, the Standard Library does have an HTTP server
implementation built in. It can even be invoked from the command line.


$ python3 -m http.server


Serving HTTP on 0.0.0.0 port 8000 ...


This server follows the old conventions established in the 1990s for serving up files from the filesystem. The path
in the HTTP request is translated into a path to search in the local filesystem. The server is designed to serve files only
at or beneath its current working directory. Files are served normally. When a directory is named, the server returns
either the content of its index.html file if one exists or a dynamically generated listing of the files inside.
Having a small web server available wherever Python is installed has gotten me out of more than one awkward
fix over the years when I have needed to transfer files between machines and none of the more specific file transfer
protocols have been available. But what are the steps to take if you need something more—if you need to put your
own software in charge of responding to HTTP requests?
This book tackles this question in two separate chapters. This chapter will look at server architecture and
deployment, answering the questions that need solutions whether your code returns documents or a programmer-
facing API. Chapter 11 will then describe the World Wide Web, and it will examine tools specific to returning HTML
pages and interacting with a user’s browser.


WSGI


In the earliest days of HTTP programming, many Python services were written as simple CGI scripts that were
invoked once per incoming request. The server carved the HTTP request into pieces and made them available to the
CGI script in its environment variables. Python programmers could either inspect these directly and print an HTTP
response to standard output or get help from the cgi module in the Standard Library.
Launching a new process for every incoming HTTP request imposed a significant limitation on server
performance, so language runtimes began implementing HTTP servers of their own. Python gained its http.server
Standard Library module, which invites programmers to implement their services by adding do_GET() and do_POST()
methods to their own subclass of BaseHTTPRequestHandler.

Free download pdf