Learning Python Network Programming

(Sean Pound) #1
Chapter 9

In the view, we check that the name supplied is valid by seeing whether it appears in
the docstrings dict. If it's okay, we build and return the corresponding HTML. If it's
not okay, then we return a 404 Not Found response to the client by calling Flask's
abort() function. This function raises a Flask HTTPException, which if not handled
by our application, will cause Flask to generate an error page and return it to the
client with the corresponding status code (in this case 404). This is a good way to fail
fast when we encounter bad requests.


Templating


You can see from our preceding views that even when cheekily omitting the usual
HTML formalities such as and the tag to save complexity,
constructing HTML in Python code is clunky. It's difficult to get a feel for the
overall page, and it's impossible for designers with no Python knowledge to work
on the page design. Also, mixing the generation of the presentation code with the
application logic makes both harder to test.


Pretty much all web frameworks solve this problem by employing the template
idiom. Since the bulk of the HTML is static, the question arises: Why keep it in
the application code at all? With templates, we extract the HTML entirely into
separate files. These then comprise HTML code, with the inclusion of some special
placeholder and logic markup to allow dynamic elements to be inserted.


Flask uses another Armin Ronacher creation, the Jinja2 templating engine, for this
task. Let's adapt our application to use templates. In your project folder, create a
folder called templates. In there, create three new text files, base.html, index.
html, and docstring.html. Fill them out as follows:


The base.html file will be like this:


<!DOCTYPE html>
<html>
<head>
<title>Python Builtins Docstrings</title>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
Free download pdf