Functional Python Programming

(Wang) #1

A Functional Approach to Web Services


Nesting the services


We can look at web request handling as a number of nested contexts. An outer
context, for example, might cover session management: examining the request to
determine if this is another request in an existing session or a new session. An inner
context might provide tokens used for form processing that can detect Cross-Site
Request Forgeries (CSRF). Another context might handle user authentication within
a session.


A conceptual view of the functions explained previously is something like this:


response= content(authentication(csrf(session(headers, request,
[forms]))))


The idea here is that each function can build on the results of the previous function.
Each function either enriches the request or rejects it because it's invalid. The
session function, for example, can use headers to determine if this is an existing
session or a new session. The csrf function will examine form input to ensure
that proper tokens were used. The CSRF handling requires a valid session. The
authentication function can return an error response for a session that lacks valid
credentials; it can enrich the request with user information when valid credentials
are present.


The content function is free from worrying about sessions, forgeries, and non-
authenticated users. It can focus on parsing the path to determine what kind of
content should be provided. In a more complex application, the content function
may include a rather complex mapping from path elements to functions that
determine the appropriate content.


The nested function view, however, still isn't quite right. The problem is that each
nested context may also need to tweak the response instead of or in addition to
tweaking the request.


We really want something more like this:


def session(headers, request, forms):
pre-process: determine session
content= csrf(headers, request, forms)
post-processes the content
return the content
def csrf(headers, request, forms):
pre-process: validate csrf tokens
content= authenticate(headers, request, forms)
post-processes the content
return the content

Free download pdf