Functional Python Programming

(Wang) #1
Chapter 15

""""""json/xml/csv/html serialization.





data = [Pair(2,3), Pair(5,7)]








serialize(""json"", ""test"", data)





(b'[{""x"": 2, ""y"": 3}, {""x"": 5, ""y"": 7}]', 'application/json')


""""""


mime, function = serializers.get(format.lower(), ('text/html',
serialize_html))


return function(title, data), mime


The overall serialize() function locates a specific serializer and a specific MIME
type that must be used in the response to characterize the results. It then calls one
of the specific serializers. We've also shown a doctest test case here. We didn't
patiently test each serializer, since showing that one works seems adequate.


We'll look at the serializers separately. What we'll see is that the serializers fall into
two groups: those that produce strings and those that produce bytes. A serializer
that produces a string will need to have the string encoded as bytes. A serializer that
produces bytes doesn't need any further work.


For the serializers, which produce strings, we need to do some function composition
with a standard convert-to-bytes. We can do functional composition using a
decorator. Here's how we can standardize the conversion to bytes:


from functools import wraps


def to_bytes(function):


@wraps(function)


def decorated(*args, **kw):


text= function(*args, **kw)


return text.encode(""utf-8"")


return decorated


We've created a small decorator named @to_bytes. This will evaluate the given
function and then encode the results using UTF-8 to get bytes. We'll show how this
is used with JSON, CSV, and HTML serializers. The XML serializer produces bytes
directly and doesn't need to be composed with this additional function.


We could also do the functional composition in the initialization of the serializers
mapping. Instead of decorating the function definition, we could decorate the
reference to the function object:


serializers = {


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


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

Free download pdf