Functional Python Programming

(Wang) #1

A Functional Approach to Web Services


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


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


}


Though this is possible, this doesn't seem to be helpful. The distinction between
serializers that produce strings and those that produce bytes isn't an important part
of the configuration.


Serializing data into the JSON or CSV format


The JSON and CSV serializers are similar functions because both rely on Python's
libraries to serialize. The libraries are inherently imperative, so the function bodies
are strict sequences of statements.


Here's the JSON serializer:


import json


@to_bytes


def serialize_json(series, data):


""""""





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








serialize_json(""test"", data)





b'[{""x"": 2, ""y"": 3}, {""x"": 5, ""y"": 7}]'


""""""


obj= [dict(x=r.x, y=r.y) for r in data]


text= json.dumps(obj, sort_keys=True)


return text


We created a list of dictionaries structure and used the json.dumps() function
to create a string representation. The JSON module requires a materialized list
object; we can't provide a lazy generator function. The sort_keys=True argument
value is essential for unit testing. However, it's not required for the application and
represents a bit of overhead.


Here's the CSV serializer:


import csv, io


@to_bytes


def serialize_csv(series, data):


""""""

Free download pdf