Functional Python Programming

(Wang) #1

A Functional Approach to Web Services


(Pair(x=10.0, y=9.14), Pair(x=8.0, y=8.14), Pair(x=13.0, y=8.74),


""""""


return raw_data[set_id]


We made this trivial expression into a function for three reasons:



  • The functional notation is slightly more consistent and a bit more flexible
    than the subscript expression

  • We can easily expand the filtering to do more

  • We can include separate unit tests in the docstring for this function


While a simple lambda would work, it wouldn't be quite as convenient to test.


For error handling, we've done exactly nothing. We've focused on what's sometimes
called the "happy path:" an ideal sequence of events. Any problems that arise in
this function will raise an exception. The WSGI wrapper function should catch all
exceptions and return an appropriate status message and error response content.


For example, it's possible that the set_id method will be wrong in some way. Rather
than obsess over all the ways it could be wrong, we'll simply allow Python to throw
an exception. Indeed, this function follows the Python I advice that, "it's better to
seek forgiveness than to ask permission." This advice is materialized in code by
avoiding "permission-seeking": there are no preparatory if statements that seek to
qualify the arguments as valid. There is only "forgiveness" handling: an exception
will be raised and handled in the WSGI wrapper. This essential advice applies to the
preceding raw data and the serialization that we will see now.


Serializing the results


Serialization is the conversion of Python data into a stream of bytes, suitable for
transmission. Each format is best described by a simple function that serializes just
that one format. A top-level generic serializer can then pick from a list of specific
serializers. The picking of serializers leads to the following collection of functions:


serializers = {


'xml': ('application/xml', serialize_xml),


'html': ('text/html', serialize_html),


'json': ('application/json', serialize_json),


'csv': ('text/csv', serialize_csv),


}


def serialize(format, title, data):

Free download pdf