Functional Python Programming

(Wang) #1
Chapter 15

However, this is impractical. It turns out that an HTTP request isn't a simple,
monolithic data structure. It actually has some required parts and some optional
parts. A request may have headers, there's a method and a path, and there may be
attachments. The attachments may include forms or uploaded files or both.


To make things more complex, a browser's form data can be sent as a query string
in the path of a GET request. Alternatively, it can be sent as an attachment to a POST
request. While there's a possibility for confusion, most web application frameworks
will create HTML form tags that provide their data via a "method=POST" statement in
the

tag; the form data will then be an attachment.


Looking more deeply into the functional view


Both HTTP response and request have headers and a body. The request can have
some attached form data. Therefore, we can think of a web server like this:


headers, content = httpd(headers, request, [uploads])


The request headers may include cookie values, which can be seen as adding
yet more arguments. Additionally, a web server is often dependent on the OS
environment in which it's running. This OS environment data can be considered as
yet more arguments being provided as part of the request.


There's a large but reasonably well defined spectrum of content. The Multipurpose
Internet Mail Extension (MIME) types define the kinds of content that a web service
might return. This can include plain text, HTML, JSON, XML, or any of the wide
variety of non-text media that a website might serve.


As we look more closely at the processing required to build a response to an HTTP
request, we'll see some common features that we'd like to reuse. This idea of reusable
elements is what leads to the creation of web service frameworks that fill a spectrum
from simple to sophisticated. The ways that functional designs allow us to reuse
functions indicate that the functional approach seems very appropriate to build
web services.


We'll look at functional design of web services by examining how we can create a
pipeline of the various elements of a service response. We'll do this by nesting the
functions for request processing so that inner elements are free from the generic
overheads, which are provided by outer elements. This also allows the outer
elements to act as filters: invalid requests can yield error responses, allowing the
inner function to focus narrowly on the application processing.

Free download pdf