Skip to content
Myr

Breaking docs up into smaller pieces

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 764b4e4 · Browse files · 8 files+443 added−445 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+443 added−445 removed

  • other:+443 added−445 removed

8 files+443 added−445 removed

added:docs/patterns/flashing.rst+79 added
1Message Flashing2================34Good applications and user interfaces are all about feedback. If the user5does not get enough feedback he will probably end up hating the6application. Flask provides a really simple way to give feedback to a7user with the flashing system. The flashing system basically makes it8possible to record a message at the end of a request and access it next9request and only next request. This is usually combined with a layout10template that does this.1112So here a full example::1314 from flask import flash, redirect, url_for, render_template1516 @app.route('/')17 def index():18 return render_template('index.html')1920 @app.route('/login', methods=['GET', 'POST'])21 def login():22 error = None23 if request.method == 'POST':24 if request.form['username'] != 'admin' or \25 request.form['password'] != 'secret':26 error = 'Invalid credentials'27 else:28 flash('You were sucessfully logged in')29 return redirect(url_for('index'))30 return render_template('login.html', error=error)3132And here the ``layout.html`` template which does the magic:3334.. sourcecode:: html+jinja3536 <!doctype html>37 <title>My Application</title>38 {% with messages = get_flashed_messages() %}39 {% if messages %}40 <ul class=flashes>41 {% for message in messages %}42 <li>{{ message }}</li>43 {% endfor %}44 </ul>45 {% endif %}46 {% endwith %}47 {% block body %}{% endblock %}4849And here the index.html template:5051.. sourcecode:: html+jinja5253 {% extends "layout.html" %}54 {% block body %}55 <h1>Overview</h1>56 <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>57 {% endblock %}5859And of course the login template:6061.. sourcecode:: html+jinja6263 {% extends "layout.html" %}64 {% block body %}65 <h1>Login</h1>66 {% if error %}67 <p class=error><strong>Error:</strong> {{ error }}68 {% endif %}69 <form action="" method=post>70 <dl>71 <dt>Username:72 <dd><input type=text name=username value="{{73 request.form.username }}">74 <dt>Password:75 <dd><input type=password name=password>76 </dl>77 <p><input type=submit value=Login>78 </form>79 {% endblock %}
added:docs/patterns/index.rst+20 added
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.1213.. toctree::14 :maxdepth: 21516 packages17 sqlite318 sqlalchemy19 templateinheritance20 flashing
added:docs/patterns/packages.rst+87 added
1.. _larger-applications:23Larger Applications4===================56For larger applications it's a good idea to use a package instead of a7module. That is quite simple. Imagine a small application looks like8this::910 /yourapplication11 /yourapplication.py12 /static13 /style.css14 /templates15 layout.html16 index.html17 login.html18 ...1920To convert that into a larger one, just create a new folder21`yourapplication` inside the existing one and move everything below it.22Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete23all `.pyc` files first, otherwise things would most likely break)2425You should then end up with something like that::2627 /yourapplication28 /yourapplication29 /__init__.py30 /static31 /style.css32 /templates33 layout.html34 index.html35 login.html36 ...3738But how do you run your application now? The naive ``python39yourapplication/__init__.py`` will not work. Let's just say that Python40does not want modules in packages to be the startup file. But that is not41a big problem, just add a new file called `runserver.py` next to the inner42`yourapplication` folder with the following contents::4344 from yourapplication import app45 app.run(debug=True)4647What did we gain from this? Now we can restructure the application a bit48into multiple modules. The only thing you have to remember is the49following quick checklist:50511. the `Flask` application object creation have to be in the52 `__init__.py` file. That way each module can import it safely and the53 `__name__` variable will resole to the correct package.542. all the view functions (the ones with a :meth:`~flask.Flask.route`55 decorator on top) have to be imported when in the `__init__.py` file.56 Not the objects itself, but the module it is in. Do the importing at57 the *bottom* of the file.5859Here an example `__init__.py`::6061 from flask import Flask62 app = Flask(__name__)6364 import yourapplication.views6566And this is what `views.py` would look like::6768 from yourapplication import app6970 @app.route('/')71 def index():72 return 'Hello World!'7374.. admonition:: Circular Imports7576 Every Python programmer hates them, and yet we just added some:77 circular imports (That's when two module depend on each one. In this78 case `views.py` depends on `__init__.py`). Be advised that this is a79 bad idea in general but here it is actually fine. The reason for this80 is81 that we are not actually using the views in `__init__.py` and just82 ensuring the module is imported and we are doing that at the bottom of83 the file.8485 There are still some problems with that approach but if you want to use86 decorators there is no way around that. Check out the87 :ref:`becomingbig` section for some inspiration how to deal with that.
added:docs/patterns/sqlalchemy.rst+100 added
1.. _sqlalchemy-pattern:23SQLAlchemy in Flask4===================56Many people prefer `SQLAlchemy`_ for database access. In this case it's7encouraged to use a package instead of a module for your flask application8and drop the models into a separate module (:ref:`larger-applications`).9Although that is not necessary but makes a lot of sense.1011There are three very common ways to use SQLAlchemy. I will outline each12of them here:1314Declarative15-----------1617The declarative extension in SQLAlchemy is the most recent method of using18SQLAlchemy. It allows you to define tables and models in one go, similar19to how Django works. In addition to the following text I recommend the20official documentation on the `declarative`_ extension.2122Here the example `database.py` module for your application::2324 from sqlalchemy import create_engine25 from sqlalchemy.orm import scoped_session, sessionmaker26 from sqlalchemy.ext.declarative import declarative_base2728 engine = create_engine('sqlite:////tmp/test.db')29 db_session = scoped_session(sessionmaker(autocommit=False,30 autoflush=False,31 bind=engine)) 32 Base = declarative_base()33 Base.query = db_session.query_property()3435 def init_db():36 Base.metadata.create_all(bind=engine)3738To define your models, just subclass the `Base` class that was created by39the code above. If you are wondering why we don't have to care about40threads here (like we did in the SQLite3 example above with the41:data:`~flask.g` object): that's because SQLAlchemy does that for us42already with the :class:`~sqlalchemy.orm.scoped_session`.4344To use SQLAlchemy in a declarative way with your application, you just45have to put the following code into your application module. Flask will46automatically remove database sessions at the end of the request for you::4748 from yourapplication.database import db_session4950 @app.after_request51 def shutdown_session(response):52 db_session.remove()53 return response5455Here an example model (put that into `models.py` for instance)::5657 from sqlalchemy import Column, Integer, String58 from yourapplication.database import Base5960 class User(Base):61 __tablename__ = 'users'62 id = Column(Integer, primary_key=True)63 name = Column(String(50), unique=True)64 email = Column(String(120), unique=True)6566 def __init__(self, name=None, email=None):67 self.name = name68 self.email = email6970 def __repr__(self):71 return '<User %r>' % (self.name, self.email)7273You can insert entries into the database like this then:7475>>> from yourapplication.database import db_session76>>> from yourapplication.models import User77>>> u = User('admin', 'admin@localhost')78>>> db_session.add(u)79>>> db_session.commit()8081Querying is simple as well:8283>>> User.query.all()84[<User u'admin'>]85>>> User.query.filter(User.name == 'admin').first()86<User u'admin'>8788.. _SQLAlchemy: http://www.sqlalchemy.org/89.. _declarative:90 http://www.sqlalchemy.org/docs/reference/ext/declarative.html9192Manual Object Relational Mapping93--------------------------------9495*coming soon*9697SQL Abstraction Layer98---------------------99100*coming soon*
added:docs/patterns/sqlite3.rst+87 added
1.. _sqlite3:23Using SQLite 3 with Flask4=========================56In Flask you can implement opening of dabase connections at the beginning7of the request and closing at the end with the8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`9decorators in combination with the special :class:`~flask.g` object.1011So here a simple example how you can use SQLite 3 with Flask::1213 import sqlite314 from flask import g1516 DATABASE = '/path/to/database.db'1718 def connect_db():19 return sqlite3.connect(DATABASE)2021 @app.before_request22 def before_request():23 g.db = connect_db()2425 @app.after_request26 def after_request(response):27 g.db.close()28 return response2930.. _easy-querying:3132Easy Querying33-------------3435Now in each request handling function you can access `g.db` to get the36current open database connection. To simplify working with SQLite a37helper function can be useful::3839 def query_db(query, args=(), one=False):40 cur = g.db.execute(query, args)41 rv = [dict((cur.description[idx][0], value)42 for idx, value in enumerate(row)) for row in cur.fetchall()]43 return (rv[0] if rv else None) if one else rv4445This handy little function makes working with the database much more46pleasant than it is by just using the raw cursor and connection objects.4748Here is how you can use it::4950 for user in query_db('select * from users'):51 print user['username'], 'has the id', user['user_id']5253Or if you just want a single result::5455 user = query_db('select * from users where username = ?',56 [the_username], one=True)57 if user is None:58 print 'No such user'59 else:60 print the_username, 'has the id', user['user_id']6162To pass variable parts to the SQL statement, use a question mark in the63statement and pass in the arguments as a list. Never directly add them to64the SQL statement with string formattings because this makes it possible65to attack the application using `SQL Injections66<http://en.wikipedia.org/wiki/SQL_injection>`_.6768Initial Schemas69---------------7071Relational databases need schemas, so applications often ship a72`schema.sql` file that creates the database. It's a good idea to provide73a function that creates the database bases on that schema. This function74can do that for you::7576 from contextlib import closing77 78 def init_db():79 with closing(connect_db()) as db:80 with app.open_resource('schema.sql') as f:81 db.cursor().executescript(f.read())82 db.commit()8384You can then create such a database from the python shell:8586>>> from yourapplication import init_db87>>> init_db()
added:docs/patterns/templateinheritance.rst+69 added
1.. _template-inheritance:23Template Inheritance4====================56The most powerful part of Jinja is template inheritance. Template inheritance7allows you to build a base "skeleton" template that contains all the common8elements of your site and defines **blocks** that child templates can override.910Sounds complicated but is very basic. It's easiest to understand it by starting11with an example.121314Base Template15-------------1617This template, which we'll call ``layout.html``, defines a simple HTML skeleton18document that you might use for a simple two-column page. It's the job of19"child" templates to fill the empty blocks with content:2021.. sourcecode:: html+jinja2223 <!doctype html>24 <html>25 <head>26 {% block head %}27 <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">28 <title>{% block title %}{% endblock %} - My Webpage</title>29 {% endblock %}30 </head>31 <body>32 <div id="content">{% block content %}{% endblock %}</div>33 <div id="footer">34 {% block footer %}35 &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.36 {% endblock %}37 </div>38 </body>3940In this example, the ``{% block %}`` tags define four blocks that child templates41can fill in. All the `block` tag does is to tell the template engine that a42child template may override those portions of the template.4344Child Template45--------------4647A child template might look like this:4849.. sourcecode:: html+jinja5051 {% extends "layout.html" %}52 {% block title %}Index{% endblock %}53 {% block head %}54 {{ super() }}55 <style type="text/css">56 .important { color: #336699; }57 </style>58 {% endblock %}59 {% block content %}60 <h1>Index</h1>61 <p class="important">62 Welcome on my awesome homepage.63 {% endblock %}6465The ``{% extends %}`` tag is the key here. It tells the template engine that66this template "extends" another template. When the template system evaluates67this template, first it locates the parent. The extends tag must be the68first tag in the template. To render the contents of a block defined in69the parent template, use ``{{ super() }}``.
modified:docs/index.rst+1 added-1 removed
38 unmodified lines
39 installation40 quickstart41 tutorial/index42 testing43 patterns43 patterns/index44 deploying45 becomingbig4647Reference
9 unmodified lines
deleted:docs/patterns.rst-444 removed
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 %}