Skip to content
Myr

patterns.rst

This file

Path

docs/patterns.rst

252 lines · 7.5 KiB

Last changed by

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

History of this file

Take it

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 1–13why, one step back
1.. _patterns:
23Patterns in Flask4=================56Certain things are common enough that the changes are high you will find7them in most web applications. For example quite a lot of applications8are using relational databases and user authentication. In that case,9changes are they will open a database connection at the beginning of the10request and get the information of the currently logged in user. At the11end of the request, the database connection is closed again.1213In Flask you can implement such things with the

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

lines 14–15why, one step back
14:meth:`~flask.Flask.before_request` and
15:meth:`~flask.Flask.after_request` decorators in combination with the

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 16–18why, one step back
16special :class:`~flask.g` object.
1718

Added a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429

lines 19–20why, one step back
19.. _database-pattern:
20

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 21–33why, one step back
21Using SQLite 3 with Flask
22-------------------------2324So here a simple example how you can use SQLite 3 with Flask::2526 import sqlite327 from flask import g2829 DATABASE = '/path/to/database.db'3031 def connect_db():32 return sqlite3.connect(DATABASE)33

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 34why, one step back
34 @app.before_request

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 35–37why, one step back
35 def before_request():
36 g.db = connect_db()37

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 38why, one step back
38 @app.after_request

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 39–42why, one step back
39 def after_request(response):
40 g.db.close()41 return response42

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 43–44why, one step back
43.. _easy-querying:
44

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 45–170why, one step back
45Easy Querying
46`````````````4748Now in each request handling function you can access `g.db` to get the49current open database connection. To simplify working with SQLite a50helper function can be useful::5152 def query_db(query, args=(), one=False):53 cur = g.db.execute(query, args)54 rv = [dict((cur.description[idx][0], value)55 for idx, value in enumerate(row)) for row in cur.fetchall()]56 return (rv[0] if rv else None) if one else rv5758This handy little function makes working with the database much more59pleasant than it is by just using the raw cursor and connection objects.6061Here is how you can use it::6263 for user in query_db('select * from users'):64 print user['username'], 'has the id', user['user_id']6566Or if you just want a single result::6768 user = query_db('select * from users where username = ?',69 [the_username], one=True)70 if user is None:71 print 'No such user'72 else:73 print the_username, 'has the id', user['user_id']7475To pass variable parts to the SQL statement, use a question mark in the76statement and pass in the arguments as a list. Never directly add them to77the SQL statement with string formattings because this makes it possible78to attack the application using `SQL Injections79<http://en.wikipedia.org/wiki/SQL_injection>`_.8081Initial Schemas82```````````````8384Relational databases need schemas, so applications often ship a85`schema.sql` file that creates the database. It's a good idea to provide86a function that creates the database bases on that schema. This function87can do that for you::8889 from contextlib import closing90 91 def init_db():92 with closing(connect_db()) as db:93 with app.open_resource('schema.sql') as f:94 db.cursor().executescript(f.read())95 db.commit()9697You can then create such a database from the python shell:9899>>> from yourapplication import init_db100>>> init_db()101102.. _template-inheritance:103104Template Inheritance105--------------------106107The most powerful part of Jinja is template inheritance. Template inheritance108allows you to build a base "skeleton" template that contains all the common109elements of your site and defines **blocks** that child templates can override.110111Sounds complicated but is very basic. It's easiest to understand it by starting112with an example.113114115Base Template116`````````````117118This template, which we'll call ``layout.html``, defines a simple HTML skeleton119document that you might use for a simple two-column page. It's the job of120"child" templates to fill the empty blocks with content:121122.. sourcecode:: html+jinja123124 <!doctype html>125 <html>126 <head>127 {% block head %}128 <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">129 <title>{% block title %}{% endblock %} - My Webpage</title>130 {% endblock %}131 </head>132 <body>133 <div id="content">{% block content %}{% endblock %}</div>134 <div id="footer">135 {% block footer %}136 &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.137 {% endblock %}138 </div>139 </body>140141In this example, the ``{% block %}`` tags define four blocks that child templates142can fill in. All the `block` tag does is to tell the template engine that a143child template may override those portions of the template.144145Child Template146``````````````147148A child template might look like this:149150.. sourcecode:: html+jinja151152 {% extends "layout.html" %}153 {% block title %}Index{% endblock %}154 {% block head %}155 {{ super() }}156 <style type="text/css">157 .important { color: #336699; }158 </style>159 {% endblock %}160 {% block content %}161 <h1>Index</h1>162 <p class="important">163 Welcome on my awesome homepage.164 {% endblock %}165166The ``{% extends %}`` tag is the key here. It tells the template engine that167this template "extends" another template. When the template system evaluates168this template, first it locates the parent. The extends tag must be the169first tag in the template. To render the contents of a block defined in170the parent template, use ``{{ super() }}``.

Flashing -> patterns documentationArmin Ronacherbefore adoptiona9d4ea8

lines 171–252why, one step back
171
172.. _message-flashing-pattern:173174Message Flashing175----------------176177Good applications and user interfaces are all about feedback. If the user178does not get enough feedback he will probably end up hating the179application. Flask provides a really simple way to give feedback to a180user with the flashing system. The flashing system basically makes it181possible to record a message at the end of a request and access it next182request and only next request. This is usually combined with a layout183template that does this.184185So here a full example::186187 from flask import flash, redirect, url_for, render_template188189 @app.route('/')190 def index():191 return render_template('index.html')192193 @app.route('/login', methods=['GET', 'POST'])194 def login():195 error = None196 if request.method == 'POST':197 if request.form['username'] != 'admin' or \198 request.form['password'] != 'secret':199 error = 'Invalid credentials'200 else:201 flash('You were sucessfully logged in')202 return redirect(url_for('index'))203 return render_template('login.html', error=error)204205And here the ``layout.html`` template which does the magic:206207.. sourcecode:: html+jinja208209 <!doctype html>210 <title>My Application</title>211 {% with messages = get_flashed_messages() %}212 {% if messages %}213 <ul class=flashes>214 {% for message in messages %}215 <li>{{ message }}</li>216 {% endfor %}217 </ul>218 {% endif %}219 {% endwith %}220 {% block body %}{% endblock %}221222And here the index.html template:223224.. sourcecode:: html+jinja225226 {% extends "layout.html" %}227 {% block body %}228 <h1>Overview</h1>229 <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>230 {% endblock %}231232And of course the login template:233234.. sourcecode:: html+jinja235236 {% extends "layout.html" %}237 {% block body %}238 <h1>Login</h1>239 {% if error %}240 <p class=error><strong>Error:</strong> {{ error }}241 {% endif %}242 <form action="" method=post>243 <dl>244 <dt>Username:245 <dd><input type=text name=username value="{{246 request.form.username }}">247 <dt>Password:248 <dd><input type=password name=password>249 </dl>250 <p><input type=submit value=Login>251 </form>252 {% endblock %}