Functional Python Programming

(Wang) #1

A Functional Approach to Web Services


Here's a very simple routing application:


SCRIPT_MAP = {


""demo"": demo_app,


""static"": static_app,


"""": welcome_app,


}


def routing(environ, start_response):


top_level= wsgiref.util.shift_path_info(environ)


app= SCRIPT_MAP.get(top_level, SCRIPT_MAP[''])


content= app(environ, start_response)


return content


This app will use the wsgiref.util.shift_path_info() function to tweak the
environment. This does a "head/tail split" on the items in the request path, available
in the environ['PATH_INFO'] dictionary. The head of the path—up to the first
"split"—will be moved into the SCRIPT_NAME item in the environment; the
PATH_INFO item will be updated to have the tail of the path. The returned value
will also be the head of the path. In the case where there's no path to parse,
the return value is None and no environment updates are made.


The routing() function uses the first item on the path to locate an application in the
SCRIPT_MAP dictionary. We use the SCRIPT_MAP[''] dictionary as a default in case
the requested path doesn't fit the mapping. This seems a little better than an HTTP
404 NOT FOUND error.


This WSGI application is a function that chooses between a number of other functions.
It's a higher-order function, since it evaluates functions defined in a data structure.


It's easy to see how a framework could generalize the path-matching process using
regular expressions. We can imagine configuring the routing() function with a
sequence of Regular Expression's (REs) and WSGI applications instead of a mapping
from a string to the WSGI application. The enhanced routing() function application
would evaluate each RE looking for a match. In the case of a match, any match.
groups() function could be used to update the environment before calling the
requested application.


Throwing exceptions during WSGI processing


One central feature of WSGI applications is that each stage along the chain is
responsible for filtering the requests. The idea is to reject faulty requests as early in the
processing as possible. Python's exception handling makes this particularly simple.

Free download pdf