Functional Python Programming

(Wang) #1
Chapter 15

text= data_page.substitute(title=series,
rows=""\n"".join(


""{0.x}{0.y}"".format(row)


for row in data)


)


return text


Our serialization function has two parts. The first part is a string.Template()
function that contains the essential HTML page. It has two placeholders where
data can be inserted into the template. The ${title} method shows where title
information can be inserted and the ${rows} method shows where the data rows
can be inserted.


The function creates individual data rows using a simple format string. These are
joined into a longer string, which is then substituted into the template.


While workable for simple cases like the preceding example, this isn't ideal for
more complex result sets. There are a number of more sophisticated template tools
to create HTML pages. A number of these include the ability to embed the looping
in the template, separate from the function that initializes serialization. Visit
https://wiki.python.org/moin/Templating for a list of alternatives.


Tracking usage


Many publicly available APIs require the use of an "API Key". The supplier of
the API requests you to sign up and provide an email address or other contact
information. In exchange for this, they provide an API Key which activates the API.


The API Key is used to authenticate access. It may also be used to authorize specific
features. Finally, it's also used to track usage. This may include throttling requests if
an API Key is used too often in a given time period.


The variations in the business models are numerous. For example, use of the API
Key is a billable event and charges are incurred. For other businesses, traffic must
reach some threshold before payments are required.


What's important is non-repudiation of the use of the API. This, in turn, means
creating API Keys that can act as a user's authentication credentials. The key must be
difficult to forge and relatively easy to verify.

Free download pdf