Skip to content
Myr

patterns.rst

This file

Path

docs/patterns.rst

443 lines · 13.6 KiB

Last changed by

fixed headersArmin Ronacherbefore adoption5348eff

History of this file

Take it

1.. _patterns:23Patterns for 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.121314.. _larger-applications:1516Larger Applications17-------------------1819For larger applications it's a good idea to use a package instead of a20module.  That is quite simple.  Imagine a small application looks like21this::2223    /yourapplication24        /yourapplication.py25        /static26            /style.css27        /templates28            layout.html29            index.html30            login.html31            ...3233To convert that into a larger one, just create a new folder34`yourapplication` inside the existing one and move everything below it.35Then rename `yourapplication.py` to `__init__.py`.  (Make sure to delete36all `.pyc` files first, otherwise things would most likely break)3738You should then end up with something like that::3940    /yourapplication41        /yourapplication42            /__init__.py43            /static44                /style.css45            /templates46                layout.html47                index.html48                login.html49                ...5051But how do you run your application now?  The naive ``python52yourapplication/__init__.py`` will not work.  Let's just say that Python53does not want modules in packages to be the startup file.  But that is not54a big problem, just add a new file called `runserver.py` next to the inner55`yourapplication` folder with the following contents::5657    from yourapplication import app58    app.run(debug=True)5960What did we gain from this?  Now we can restructure the application a bit61into multiple modules.  The only thing you have to remember is the62following quick checklist:63641. the `Flask` application object creation have to be in the65   `__init__.py` file.  That way each module can import it safely and the66   `__name__` variable will resole to the correct package.672. all the view functions (the ones with a :meth:`~flask.Flask.route`68   decorator on top) have to be imported when in the `__init__.py` file.69   Not the objects itself, but the module it is in.  Do the importing at70   the *bottom* of the file.7172Here an example `__init__.py`::7374    from flask import Flask75    app = Flask(__name__)7677    import yourapplication.views7879And this is what `views.py` would look like::8081    from yourapplication import app8283    @app.route('/')84    def index():85        return 'Hello World!'8687.. admonition:: Circular Imports8889   Every Python programmer hates it, and yet we just did that: circular90   imports (That's when two module depend on each one.  In this case91   `views.py` depends on `__init__.py`).  Be advised that this is a bad92   idea in general but here it is actually fine.  The reason for this is93   that we are not actually using the views in `__init__.py` and just94   ensuring the module is imported and we are doing that at the bottom of95   the file.9697   There are still some problems with that approach but if you want to use98   decorators there is no way around that.  Check out the99   :ref:`becomingbig` section for some inspiration how to deal with that.100101102.. _database-pattern:103104Using SQLite 3 with Flask105-------------------------106107In Flask you can implement opening of dabase connections at the beginning108of the request and closing at the end with the109:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`110decorators in combination with the special :class:`~flask.g` object.111112So here a simple example how you can use SQLite 3 with Flask::113114    import sqlite3115    from flask import g116117    DATABASE = '/path/to/database.db'118119    def connect_db():120        return sqlite3.connect(DATABASE)121122    @app.before_request123    def before_request():124        g.db = connect_db()125126    @app.after_request127    def after_request(response):128        g.db.close()129        return response130131.. _easy-querying:132133Easy Querying134`````````````135136Now in each request handling function you can access `g.db` to get the137current open database connection.  To simplify working with SQLite a138helper function can be useful::139140    def query_db(query, args=(), one=False):141        cur = g.db.execute(query, args)142        rv = [dict((cur.description[idx][0], value)143                   for idx, value in enumerate(row)) for row in cur.fetchall()]144        return (rv[0] if rv else None) if one else rv145146This handy little function makes working with the database much more147pleasant than it is by just using the raw cursor and connection objects.148149Here is how you can use it::150151    for user in query_db('select * from users'):152        print user['username'], 'has the id', user['user_id']153154Or if you just want a single result::155156    user = query_db('select * from users where username = ?',157                    [the_username], one=True)158    if user is None:159        print 'No such user'160    else:161        print the_username, 'has the id', user['user_id']162163To pass variable parts to the SQL statement, use a question mark in the164statement and pass in the arguments as a list.  Never directly add them to165the SQL statement with string formattings because this makes it possible166to attack the application using `SQL Injections167<http://en.wikipedia.org/wiki/SQL_injection>`_.168169Initial Schemas170```````````````171172Relational databases need schemas, so applications often ship a173`schema.sql` file that creates the database.  It's a good idea to provide174a function that creates the database bases on that schema.  This function175can do that for you::176177    from contextlib import closing178    179    def init_db():180        with closing(connect_db()) as db:181            with app.open_resource('schema.sql') as f:182                db.cursor().executescript(f.read())183            db.commit()184185You can then create such a database from the python shell:186187>>> from yourapplication import init_db188>>> init_db()189190191.. _sqlalchemy-pattern:192193SQLAlchemy in Flask194-------------------195196Many people prefer `SQLAlchemy`_ for database access.  In this case it's197encouraged to use a package instead of a module for your flask application198and drop the models into a separate module (:ref:`larger-applications`).199Although that is not necessary but makes a lot of sense.200201There are three very common ways to use SQLAlchemy.  I will outline each202of them here:203204Declarative205```````````206207The declarative extension in SQLAlchemy is the most recent method of using208SQLAlchemy.  It allows you to define tables and models in one go, similar209to how Django works.  In addition to the following text I recommend the210official documentation on the `declarative`_ extension.211212Here the example `database.py` module for your application::213214    from sqlalchemy import create_engine215    from sqlalchemy.orm import scoped_session, sessionmaker216    from sqlalchemy.ext.declarative import declarative_base217218    engine = create_engine('sqlite:////tmp/test.db')219    db_session = scoped_session(sessionmaker(autocommit=False,220                                             autoflush=False,221                                             bind=engine)) 222    Base = declarative_base()223    Base.query = db_session.query_property()224225    def init_db():226        Base.metadata.create_all(bind=engine)227228To define your models, just subclass the `Base` class that was created by229the code above.  If you are wondering why we don't have to care about230threads here (like we did in the SQLite3 example above with the231:data:`~flask.g` object): that's because SQLAlchemy does that for us232already with the :class:`~sqlalchemy.orm.scoped_session`.233234To use SQLAlchemy in a declarative way with your application, you just235have to put the following code into your application module.  Flask will236automatically remove database sessions at the end of the request for you::237238    from yourapplication.database import db_session239240    @app.after_request241    def shutdown_session(response):242        db_session.remove()243        return response244245Here an example model (put that into `models.py` for instance)::246247    from sqlalchemy import Column, Integer, String248    from yourapplication.database import Base249250    class User(Base):251        __tablename__ = 'users'252        id = Column(Integer, primary_key=True)253        name = Column(String(50), unique=True)254        email = Column(String(120), unique=True)255256        def __init__(self, name=None, email=None):257            self.name = name258            self.email = email259260        def __repr__(self):261            return '<User %r>' % (self.name, self.email)262263You can insert entries into the database like this then:264265>>> from yourapplication.database import db_session266>>> from yourapplication.models import User267>>> u = User('admin', 'admin@localhost')268>>> db_session.add(u)269>>> db_session.commit()270271Querying is simple as well:272273>>> User.query.all()274[<User u'admin'>]275>>> User.query.filter(User.name == 'admin').first()276<User u'admin'>277278.. _SQLAlchemy: http://www.sqlalchemy.org/279.. _declarative:280   http://www.sqlalchemy.org/docs/reference/ext/declarative.html281282Manual Object Relational Mapping283````````````````````````````````284285*coming soon*286287SQL Abstraction Layer288`````````````````````289290*coming soon*291292293.. _template-inheritance:294295Template Inheritance296--------------------297298The most powerful part of Jinja is template inheritance. Template inheritance299allows you to build a base "skeleton" template that contains all the common300elements of your site and defines **blocks** that child templates can override.301302Sounds complicated but is very basic. It's easiest to understand it by starting303with an example.304305306Base Template307`````````````308309This template, which we'll call ``layout.html``, defines a simple HTML skeleton310document that you might use for a simple two-column page. It's the job of311"child" templates to fill the empty blocks with content:312313.. sourcecode:: html+jinja314315    <!doctype html>316    <html>317      <head>318        {% block head %}319        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">320        <title>{% block title %}{% endblock %} - My Webpage</title>321        {% endblock %}322      </head>323    <body>324      <div id="content">{% block content %}{% endblock %}</div>325      <div id="footer">326        {% block footer %}327        &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.328        {% endblock %}329      </div>330    </body>331332In this example, the ``{% block %}`` tags define four blocks that child templates333can fill in. All the `block` tag does is to tell the template engine that a334child template may override those portions of the template.335336Child Template337``````````````338339A child template might look like this:340341.. sourcecode:: html+jinja342343    {% extends "layout.html" %}344    {% block title %}Index{% endblock %}345    {% block head %}346      {{ super() }}347      <style type="text/css">348        .important { color: #336699; }349      </style>350    {% endblock %}351    {% block content %}352      <h1>Index</h1>353      <p class="important">354        Welcome on my awesome homepage.355    {% endblock %}356357The ``{% extends %}`` tag is the key here. It tells the template engine that358this template "extends" another template.  When the template system evaluates359this template, first it locates the parent.  The extends tag must be the360first tag in the template.  To render the contents of a block defined in361the parent template, use ``{{ super() }}``.362363.. _message-flashing-pattern:364365Message Flashing366----------------367368Good applications and user interfaces are all about feedback.  If the user369does not get enough feedback he will probably end up hating the370application.  Flask provides a really simple way to give feedback to a371user with the flashing system.  The flashing system basically makes it372possible to record a message at the end of a request and access it next373request and only next request.  This is usually combined with a layout374template that does this.375376So here a full example::377378    from flask import flash, redirect, url_for, render_template379380    @app.route('/')381    def index():382        return render_template('index.html')383384    @app.route('/login', methods=['GET', 'POST'])385    def login():386        error = None387        if request.method == 'POST':388            if request.form['username'] != 'admin' or \389               request.form['password'] != 'secret':390                error = 'Invalid credentials'391            else:392                flash('You were sucessfully logged in')393                return redirect(url_for('index'))394        return render_template('login.html', error=error)395396And here the ``layout.html`` template which does the magic:397398.. sourcecode:: html+jinja399400   <!doctype html>401   <title>My Application</title>402   {% with messages = get_flashed_messages() %}403     {% if messages %}404       <ul class=flashes>405       {% for message in messages %}406         <li>{{ message }}</li>407       {% endfor %}408       </ul>409     {% endif %}410   {% endwith %}411   {% block body %}{% endblock %}412413And here the index.html template:414415.. sourcecode:: html+jinja416417   {% extends "layout.html" %}418   {% block body %}419     <h1>Overview</h1>420     <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>421   {% endblock %}422423And of course the login template:424425.. sourcecode:: html+jinja426427   {% extends "layout.html" %}428   {% block body %}429     <h1>Login</h1>430     {% if error %}431       <p class=error><strong>Error:</strong> {{ error }}432     {% endif %}433     <form action="" method=post>434       <dl>435         <dt>Username:436         <dd><input type=text name=username value="{{437             request.form.username }}">438         <dt>Password:439         <dd><input type=password name=password>440       </dl>441       <p><input type=submit value=Login>442     </form>443   {% endblock %}