Functional Python Programming

(Wang) #1

A Functional Approach to Web Services


x.text= str(row.x)


y= XML.SubElement(row_xml, ""y"")


y.text= str(row.y)


return XML.tostring(doc, encoding='utf-8')


We created a top-level element, , and placed subelements underneath
that top element. Within each subelement, we've created and tags and
assigned text content to each tag.


The interface for building an XML document using the ElementTree library tends
to be heavily imperative. This makes it a poor fit for an otherwise functional design.
In addition to the imperative style, note that we haven't created a DTD or XSD. We
have not properly assigned a namespace to our tags. We also omitted the <?xml
version=""1.0""?> processing instruction that is generally the first item in an
XML document.


A more sophisticated serialization library would be helpful. There are many
to choose from. Visit https://wiki.python.org/moin/PythonXml for a list
of alternatives.


Serializing data into HTML


In our final example of serialization, we'll look at the complexity of creating an
HTML document. The complexity arises because in HTML, we're expected to
provide an entire web page with some context information. Here's one way to
tackle this HTML problem:


import string


data_page = string.Template(""""""


Series ${title}

Series ${title}




${rows}
xy
"""""")

@to_bytes


def serialize_html(series, data):


""""""





data = [Pair(2,3), Pair(5,7)]
serialize_html(""test"", data) #doctest: +ELLIPSIS
b'...23\n5


7...
""""""


Free download pdf