patterns.rst
This file
Path
docs/patterns.rst
250 lines · 7.5 KiB
Last changed by
Added a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429
History of this fileTake it
And finished documentation for most parts.Armin Ronacherbefore adoption727c701
lines 1–18why, one step back1.. _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 the14:meth:`~flask.Flask.request_init` and15:meth:`~flask.Flask.request_shutdown` decorators in combination with the16special :class:`~flask.g` object.1718Added a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429
lines 19–20why, one step back19.. _database-pattern:20And finished documentation for most parts.Armin Ronacherbefore adoption727c701
lines 21–168why, one step back21Using SQLite 3 with Flask22-------------------------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)3334 @app.request_init35 def before_request():36 g.db = connect_db()3738 @app.request_shutdown39 def after_request(response):40 g.db.close()41 return response4243Easy Querying44`````````````4546Now in each request handling function you can access `g.db` to get the47current open database connection. To simplify working with SQLite a48helper function can be useful::4950 def query_db(query, args=(), one=False):51 cur = g.db.execute(query, args)52 rv = [dict((cur.description[idx][0], value)53 for idx, value in enumerate(row)) for row in cur.fetchall()]54 return (rv[0] if rv else None) if one else rv5556This handy little function makes working with the database much more57pleasant than it is by just using the raw cursor and connection objects.5859Here is how you can use it::6061 for user in query_db('select * from users'):62 print user['username'], 'has the id', user['user_id']6364Or if you just want a single result::6566 user = query_db('select * from users where username = ?',67 [the_username], one=True)68 if user is None:69 print 'No such user'70 else:71 print the_username, 'has the id', user['user_id']7273To pass variable parts to the SQL statement, use a question mark in the74statement and pass in the arguments as a list. Never directly add them to75the SQL statement with string formattings because this makes it possible76to attack the application using `SQL Injections77<http://en.wikipedia.org/wiki/SQL_injection>`_.7879Initial Schemas80```````````````8182Relational databases need schemas, so applications often ship a83`schema.sql` file that creates the database. It's a good idea to provide84a function that creates the database bases on that schema. This function85can do that for you::8687 from contextlib import closing88 89 def init_db():90 with closing(connect_db()) as db:91 with app.open_resource('schema.sql') as f:92 db.cursor().executescript(f.read())93 db.commit()9495You can then create such a database from the python shell:9697>>> from yourapplication import init_db98>>> init_db()99100.. _template-inheritance:101102Template Inheritance103--------------------104105The most powerful part of Jinja is template inheritance. Template inheritance106allows you to build a base "skeleton" template that contains all the common107elements of your site and defines **blocks** that child templates can override.108109Sounds complicated but is very basic. It's easiest to understand it by starting110with an example.111112113Base Template114`````````````115116This template, which we'll call ``layout.html``, defines a simple HTML skeleton117document that you might use for a simple two-column page. It's the job of118"child" templates to fill the empty blocks with content:119120.. sourcecode:: html+jinja121122 <!doctype html>123 <html>124 <head>125 {% block head %}126 <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">127 <title>{% block title %}{% endblock %} - My Webpage</title>128 {% endblock %}129 </head>130 <body>131 <div id="content">{% block content %}{% endblock %}</div>132 <div id="footer">133 {% block footer %}134 © Copyright 2010 by <a href="http://domain.invalid/">you</a>.135 {% endblock %}136 </div>137 </body>138139In this example, the ``{% block %}`` tags define four blocks that child templates140can fill in. All the `block` tag does is to tell the template engine that a141child template may override those portions of the template.142143Child Template144``````````````145146A child template might look like this:147148.. sourcecode:: html+jinja149150 {% extends "layout.html" %}151 {% block title %}Index{% endblock %}152 {% block head %}153 {{ super() }}154 <style type="text/css">155 .important { color: #336699; }156 </style>157 {% endblock %}158 {% block content %}159 <h1>Index</h1>160 <p class="important">161 Welcome on my awesome homepage.162 {% endblock %}163164The ``{% extends %}`` tag is the key here. It tells the template engine that165this template "extends" another template. When the template system evaluates166this template, first it locates the parent. The extends tag must be the167first tag in the template. To render the contents of a block defined in168the parent template, use ``{{ super() }}``.Flashing -> patterns documentationArmin Ronacherbefore adoptiona9d4ea8
lines 169–250why, one step back169170.. _message-flashing-pattern:171172Message Flashing173----------------174175Good applications and user interfaces are all about feedback. If the user176does not get enough feedback he will probably end up hating the177application. Flask provides a really simple way to give feedback to a178user with the flashing system. The flashing system basically makes it179possible to record a message at the end of a request and access it next180request and only next request. This is usually combined with a layout181template that does this.182183So here a full example::184185 from flask import flash, redirect, url_for, render_template186187 @app.route('/')188 def index():189 return render_template('index.html')190191 @app.route('/login', methods=['GET', 'POST'])192 def login():193 error = None194 if request.method == 'POST':195 if request.form['username'] != 'admin' or \196 request.form['password'] != 'secret':197 error = 'Invalid credentials'198 else:199 flash('You were sucessfully logged in')200 return redirect(url_for('index'))201 return render_template('login.html', error=error)202203And here the ``layout.html`` template which does the magic:204205.. sourcecode:: html+jinja206207 <!doctype html>208 <title>My Application</title>209 {% with messages = get_flashed_messages() %}210 {% if messages %}211 <ul class=flashes>212 {% for message in messages %}213 <li>{{ message }}</li>214 {% endfor %}215 </ul>216 {% endif %}217 {% endwith %}218 {% block body %}{% endblock %}219220And here the index.html template:221222.. sourcecode:: html+jinja223224 {% extends "layout.html" %}225 {% block body %}226 <h1>Overview</h1>227 <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>228 {% endblock %}229230And of course the login template:231232.. sourcecode:: html+jinja233234 {% extends "layout.html" %}235 {% block body %}236 <h1>Login</h1>237 {% if error %}238 <p class=error><strong>Error:</strong> {{ error }}239 {% endif %}240 <form action="" method=post>241 <dl>242 <dt>Username:243 <dd><input type=text name=username value="{{244 request.form.username }}">245 <dt>Password:246 <dd><input type=password name=password>247 </dl>248 <p><input type=submit value=Login>249 </form>250 {% endblock %}