Skip to content
Myr

Restructured documentation a bit.

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 fb2d2e4 · Browse files · 2 files+213 added−8 removed
This commit

State

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

Diff stats

2 files+213 added−8 removed

  • other:+213 added−8 removed

2 files+213 added−8 removed

modified:docs/index.rst+30 added-2 removed
12 unmodified lines
13you rather want to dive into all the internal parts of Flask, check out14the :ref:`api` documentation. Common patterns are described in the15:ref:`patterns` section.1617Flask also depends on two external libraries: the `Jinja2`_ template18engine and the `Werkzeug`_ WSGI toolkit. both of which are not documented19here. If you want to dive into their documentation check out the20following links:2122- `Jinja2 Documentation <http://jinja.pocoo.org/2/documentation/>`_23- `Werkzeug Documentation <http://werkzeug.pocoo.org/documentation/>`_2425.. _Jinja2: http://jinja.pocoo.org/2/26.. _Werkzeug: http://werkzeug.pocoo.org/2728Textual Documentation29---------------------3031This part of the documentation is written text and should give you an idea32how to work with Flask. It's a series of step-by-step instructions for33web development.3435.. toctree::36 :maxdepth: 23738 foreword39 installation40 quickstart41 tutorial42 testing43 patterns25 api44 deploying27 testing45 becomingbig4647Reference48---------4950If you are looking for information on a specific function, class or51method, this part of the documentation is for you:5253.. toctree::54 :maxdepth: 25556 api
modified:docs/patterns.rst+183 added-6 removed
1.. _patterns:23Patterns in Flask4=================3Patterns 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.1213In Flask you can implement such things with the14:meth:`~flask.Flask.before_request` and15:meth:`~flask.Flask.after_request` decorators in combination with the16special :class:`~flask.g` object.1314.. _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 one module depends on another 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 g
70 unmodified lines
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 modules 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, subclass the `Base` class the above code generated.229230To use SQLAlchemy in a declarative way with your application, you just231have to put the following code into your application module Flask will232automatically remove database sessions at the end of the request for you::233234 from yourapplication.database import db_session235236 @app.after_request237 def shutdown_session(response):238 db_session.remove()239 return response240241Here an example model (put that into `models.py` for instance)::242243 from sqlalchemy import Column, Integer, String244 from yourapplication.database import Base245246 class User(Base):247 __tablename__ = 'users'248 id = Column(Integer, primary_key=True)249 name = Column(String(50), unique=True)250 email = Column(String(120), unique=True)251252 def __init__(self, name=None, email=None):253 self.name = name254 self.email = email255256 def __repr__(self):257 return '<User %r>' % (self.name, self.email)258259You can insert entries into the database like this then:260261>>> from yourapplication.database import db_session262>>> from yourapplication.models import User263>>> u = User('admin', 'admin@localhost')264>>> db_session.add(u)265>>> db_session.commit()266267Querying is simple as well:268269>>> User.query.all()270[<User u'admin'>]271>>> User.query.filter(User.name == 'admin').first()272<User u'admin'>273274.. _SQLAlchemy: http://www.sqlalchemy.org/275.. _declarative:276 http://www.sqlalchemy.org/docs/reference/ext/declarative.html277278279.. _template-inheritance:280281Template Inheritance282--------------------
147 unmodified lines