Learning Python Network Programming

(Sean Pound) #1

Applications for the Web


The index.html file will be like this:


{% extends "base.html" %}
{% block body %}
<h1>Python Builtins Docstrings</h1>
<div>
{% for func in funcs %}
<div class="menuitem link">
<a href="/functions/{{ func }}">{{ func }}</a>
</div>
{% endfor %}
</table>
{% endblock %}

The docstring.html file will be like this:


{% extends 'base.html' %}
{% block body %}
<h1>{{ func_name }}</h1>
<pre>{{ doc }}</pre>
<p><a href="/">Home</a></p>
{% endblock %}

Add render_template to the from flask import... line at the top of
tinyflaskapp.py, then modify your views to look like this:


@app.route('/')
def index():
return render_template('index.html', funcs=sorted(docstrings))

@app.route('/functions/<func_name>')
def show_docstring(func_name):
func_name = func_name.lower()
if func_name in docstrings:
return render_template('docstring.html',
func_name=func_name,
doc=docstrings[func_name])
else:
abort(404)

This code can be found in the 2-templates folder of this chapter's source code.


Notice how the views become much simpler, and the HTML is much more
readable now? Instead of composing a return string by hand, our views simply
call render_template() and return the result.

Free download pdf