Skip to content
Myr

patterns.rst

This file

Path

docs/patterns.rst

444 lines · 13.6 KiB

Last changed by

New style for the documentation. Looks more like the website now.Armin Ronacherbefore adoptionbcf347f

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 them, and yet we just added some:90   circular imports (That's when two module depend on each one.  In this91   case `views.py` depends on `__init__.py`).  Be advised that this is a92   bad idea in general but here it is actually fine.  The reason for this93   is94   that we are not actually using the views in `__init__.py` and just95   ensuring the module is imported and we are doing that at the bottom of96   the file.9798   There are still some problems with that approach but if you want to use99   decorators there is no way around that.  Check out the100   :ref:`becomingbig` section for some inspiration how to deal with that.101102103.. _database-pattern:104105Using SQLite 3 with Flask106-------------------------107108In Flask you can implement opening of dabase connections at the beginning109of the request and closing at the end with the110:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`111decorators in combination with the special :class:`~flask.g` object.112113So here a simple example how you can use SQLite 3 with Flask::114115    import sqlite3116    from flask import g117118    DATABASE = '/path/to/database.db'119120    def connect_db():121        return sqlite3.connect(DATABASE)122123    @app.before_request124    def before_request():125        g.db = connect_db()126127    @app.after_request128    def after_request(response):129        g.db.close()130        return response131132.. _easy-querying:133134Easy Querying135`````````````136137Now in each request handling function you can access `g.db` to get the138current open database connection.  To simplify working with SQLite a139helper function can be useful::140141    def query_db(query, args=(), one=False):142        cur = g.db.execute(query, args)143        rv = [dict((cur.description[idx][0], value)144                   for idx, value in enumerate(row)) for row in cur.fetchall()]145        return (rv[0] if rv else None) if one else rv146147This handy little function makes working with the database much more148pleasant than it is by just using the raw cursor and connection objects.149150Here is how you can use it::151152    for user in query_db('select * from users'):153        print user['username'], 'has the id', user['user_id']154155Or if you just want a single result::156157    user = query_db('select * from users where username = ?',158                    [the_username], one=True)159    if user is None:160        print 'No such user'161    else:162        print the_username, 'has the id', user['user_id']163164To pass variable parts to the SQL statement, use a question mark in the165statement and pass in the arguments as a list.  Never directly add them to166the SQL statement with string formattings because this makes it possible167to attack the application using `SQL Injections168<http://en.wikipedia.org/wiki/SQL_injection>`_.169170Initial Schemas171```````````````172173Relational databases need schemas, so applications often ship a174`schema.sql` file that creates the database.  It's a good idea to provide175a function that creates the database bases on that schema.  This function176can do that for you::177178    from contextlib import closing179    180    def init_db():181        with closing(connect_db()) as db:182            with app.open_resource('schema.sql') as f:183                db.cursor().executescript(f.read())184            db.commit()185186You can then create such a database from the python shell:187188>>> from yourapplication import init_db189>>> init_db()190191192.. _sqlalchemy-pattern:193194SQLAlchemy in Flask195-------------------196197Many people prefer `SQLAlchemy`_ for database access.  In this case it's198encouraged to use a package instead of a module for your flask application199and drop the models into a separate module (:ref:`larger-applications`).200Although that is not necessary but makes a lot of sense.201202There are three very common ways to use SQLAlchemy.  I will outline each203of them here:204205Declarative206```````````207208The declarative extension in SQLAlchemy is the most recent method of using209SQLAlchemy.  It allows you to define tables and models in one go, similar210to how Django works.  In addition to the following text I recommend the211official documentation on the `declarative`_ extension.212213Here the example `database.py` module for your application::214215    from sqlalchemy import create_engine216    from sqlalchemy.orm import scoped_session, sessionmaker217    from sqlalchemy.ext.declarative import declarative_base218219    engine = create_engine('sqlite:////tmp/test.db')220    db_session = scoped_session(sessionmaker(autocommit=False,221                                             autoflush=False,222                                             bind=engine)) 223    Base = declarative_base()224    Base.query = db_session.query_property()225226    def init_db():227        Base.metadata.create_all(bind=engine)228229To define your models, just subclass the `Base` class that was created by230the code above.  If you are wondering why we don't have to care about231threads here (like we did in the SQLite3 example above with the232:data:`~flask.g` object): that's because SQLAlchemy does that for us233already with the :class:`~sqlalchemy.orm.scoped_session`.234235To use SQLAlchemy in a declarative way with your application, you just236have to put the following code into your application module.  Flask will237automatically remove database sessions at the end of the request for you::238239    from yourapplication.database import db_session240241    @app.after_request242    def shutdown_session(response):243        db_session.remove()244        return response245246Here an example model (put that into `models.py` for instance)::247248    from sqlalchemy import Column, Integer, String249    from yourapplication.database import Base250251    class User(Base):252        __tablename__ = 'users'253        id = Column(Integer, primary_key=True)254        name = Column(String(50), unique=True)255        email = Column(String(120), unique=True)256257        def __init__(self, name=None, email=None):258            self.name = name259            self.email = email260261        def __repr__(self):262            return '<User %r>' % (self.name, self.email)263264You can insert entries into the database like this then:265266>>> from yourapplication.database import db_session267>>> from yourapplication.models import User268>>> u = User('admin', 'admin@localhost')269>>> db_session.add(u)270>>> db_session.commit()271272Querying is simple as well:273274>>> User.query.all()275[<User u'admin'>]276>>> User.query.filter(User.name == 'admin').first()277<User u'admin'>278279.. _SQLAlchemy: http://www.sqlalchemy.org/280.. _declarative:281   http://www.sqlalchemy.org/docs/reference/ext/declarative.html282283Manual Object Relational Mapping284````````````````````````````````285286*coming soon*287288SQL Abstraction Layer289`````````````````````290291*coming soon*292293294.. _template-inheritance:295296Template Inheritance297--------------------298299The most powerful part of Jinja is template inheritance. Template inheritance300allows you to build a base "skeleton" template that contains all the common301elements of your site and defines **blocks** that child templates can override.302303Sounds complicated but is very basic. It's easiest to understand it by starting304with an example.305306307Base Template308`````````````309310This template, which we'll call ``layout.html``, defines a simple HTML skeleton311document that you might use for a simple two-column page. It's the job of312"child" templates to fill the empty blocks with content:313314.. sourcecode:: html+jinja315316    <!doctype html>317    <html>318      <head>319        {% block head %}320        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">321        <title>{% block title %}{% endblock %} - My Webpage</title>322        {% endblock %}323      </head>324    <body>325      <div id="content">{% block content %}{% endblock %}</div>326      <div id="footer">327        {% block footer %}328        &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.329        {% endblock %}330      </div>331    </body>332333In this example, the ``{% block %}`` tags define four blocks that child templates334can fill in. All the `block` tag does is to tell the template engine that a335child template may override those portions of the template.336337Child Template338``````````````339340A child template might look like this:341342.. sourcecode:: html+jinja343344    {% extends "layout.html" %}345    {% block title %}Index{% endblock %}346    {% block head %}347      {{ super() }}348      <style type="text/css">349        .important { color: #336699; }350      </style>351    {% endblock %}352    {% block content %}353      <h1>Index</h1>354      <p class="important">355        Welcome on my awesome homepage.356    {% endblock %}357358The ``{% extends %}`` tag is the key here. It tells the template engine that359this template "extends" another template.  When the template system evaluates360this template, first it locates the parent.  The extends tag must be the361first tag in the template.  To render the contents of a block defined in362the parent template, use ``{{ super() }}``.363364.. _message-flashing-pattern:365366Message Flashing367----------------368369Good applications and user interfaces are all about feedback.  If the user370does not get enough feedback he will probably end up hating the371application.  Flask provides a really simple way to give feedback to a372user with the flashing system.  The flashing system basically makes it373possible to record a message at the end of a request and access it next374request and only next request.  This is usually combined with a layout375template that does this.376377So here a full example::378379    from flask import flash, redirect, url_for, render_template380381    @app.route('/')382    def index():383        return render_template('index.html')384385    @app.route('/login', methods=['GET', 'POST'])386    def login():387        error = None388        if request.method == 'POST':389            if request.form['username'] != 'admin' or \390               request.form['password'] != 'secret':391                error = 'Invalid credentials'392            else:393                flash('You were sucessfully logged in')394                return redirect(url_for('index'))395        return render_template('login.html', error=error)396397And here the ``layout.html`` template which does the magic:398399.. sourcecode:: html+jinja400401   <!doctype html>402   <title>My Application</title>403   {% with messages = get_flashed_messages() %}404     {% if messages %}405       <ul class=flashes>406       {% for message in messages %}407         <li>{{ message }}</li>408       {% endfor %}409       </ul>410     {% endif %}411   {% endwith %}412   {% block body %}{% endblock %}413414And here the index.html template:415416.. sourcecode:: html+jinja417418   {% extends "layout.html" %}419   {% block body %}420     <h1>Overview</h1>421     <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>422   {% endblock %}423424And of course the login template:425426.. sourcecode:: html+jinja427428   {% extends "layout.html" %}429   {% block body %}430     <h1>Login</h1>431     {% if error %}432       <p class=error><strong>Error:</strong> {{ error }}433     {% endif %}434     <form action="" method=post>435       <dl>436         <dt>Username:437         <dd><input type=text name=username value="{{438             request.form.username }}">439         <dt>Password:440         <dd><input type=password name=password>441       </dl>442       <p><input type=submit value=Login>443     </form>444   {% endblock %}