Functional Python Programming

(Wang) #1
Chapter 15

The techniques for a user agent to handle 3xx and 401 codes aren't deeply stateful.
A simple recursion can be used. If the status doesn't indicate a redirection, it is the
base case, and the function has a result. If redirection is required, the function can be
called recursively with the redirected address.


Looking at the other end of the protocol, a static content server should also be
stateless. There are two layers to the HTTP protocol: the TCP/IP socket machinery
and a higher layer HTTP structure that depends on the lower level sockets. The
lower level details are handled by the scoketserver library. The Python http.
server library is one of the libraries that provide a higher level implementation.


We can use the http.server library as follows:


from http.server import HTTPServer, SimpleHTTPRequestHandler


running = True


httpd = HTTPServer(('localhost',8080), SimpleHTTPRequestHandler)


while running:


httpd.handle_request()


httpd.shutdown()


We created a server object, and assigned it to the httpd variable. We provided the
address and port number to which we'll listen for connection requests. The TCP/IP
protocol will spawn a connection on a separate port. The HTTP protocol will read the
request from this other port and create an instance of the handler.


In this example, we provided SimpleHTTPRequestHandler as the class to instantiate
with each request. This class must implement a minimal interface, which will send
headers and then send the body of the response to the client. This particular class
will serve files from the local directory. If we wish to customize this, we can create
a subclass, which implements methods such as do_GET() and do_POST() to alter
the behavior.


Often, we use the serve_forever() method instead of writing our own loop. We've
shown the loop here to clarify that the server must, generally, be crashed. If we want
to close the server down politely, we'll require some way in which we can change the
value of the shutdown variable. The Ctrl + C signal, for example, is commonly used
for this.

Free download pdf