Rolling Your Own Servers in Python
Most of the Internet modules we looked at in the last few chapters deal with client-side interfaces such as FTP and POP, or special server-side protocols such as CGI that hide the underlying server itself. If you want to build servers in Python by hand, you can do so either manually or by using higher-level tools.
Coding Solutions
We saw
the sort of code needed to build servers manually in Chapter 10. Python programs typically implement servers
either by using raw socket calls with threads, forks, or selects to
handle clients in parallel, or by using the
SocketServer
module.
In either case, to serve requests made in terms of higher-level protocols such as FTP, NNTP, and HTTP, you must listen on the protocol’s port and add appropriate code to handle the protocol’s message conventions. If you go this route, the client-side protocol modules in Python’s standard library can help you understand the message conventions used. You may also be able to uncover protocol server examples in the Demos and Tools directories of the Python source distribution and on the Net at large (search http://www.python.org). See prior chapters for more details on writing socket-based servers.
As a higher-level interface, Python
also comes with precoded HTTP web protocol server implementations, in
the form of three standard modules. BaseHTTPServer
implements the server itself; this class is derived from the standard
SocketServer.TCPServer
class.
SimpleHTTPServer
Get Programming Python, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.