Functional Python Programming

(Wang) #1

A Functional Approach to Web Services


Creating the WSGI application


First, we'll use a simple URL pattern-matching expression to define the one and only
routing in our application. In a larger or more complex application, we might have
more than one such patterns:


import re


path_pat= re.compile(r""^/anscombe/(?P.*?)/?$"")


This pattern allows us to define an overall "script" in the WSGI sense at the top level
of the path. In this case, the script is "anscombe". We'll take the next level of the path
as a dataset to select from the Anscombe Quartet. The dataset value should be one of
I, II, III, or IV.


We used a named parameter for the selection criteria. In many cases, RESTful APIs
are described using a syntax, as follows:


/anscombe/{dataset}/


We translated this idealized pattern into a proper, regular expression, and preserved
the name of the dataset selector in the path.


Here's the kind of unit test that demonstrates how this pattern works:


test_pattern= """"""





m1= path_pat.match(""/anscombe/I"")








m1.groupdict()





{'dataset': 'I'}





m2= path_pat.match(""/anscombe/II/"")








m2.groupdict()





{'dataset': 'II'}





m3= path_pat.match(""/anscombe/"")








m3.groupdict()





{'dataset': ''}


""""""


We can include the three previously mentioned examples as part of the overall
doctest using the following command:


test = {


""test_pattern"": test_pattern,


}

Free download pdf