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
Provenance
- Commit
26f86b1- Tree
0785838- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fb2d2e4
2 files changed+213 added−8 removed
modified:docs/index.rst+30 added-2 removed
12 unmodified lines13 you rather want to dive into all the internal parts of Flask, check out14 the :ref:`api` documentation. Common patterns are described in the15 :ref:`patterns` section.16 17+Flask also depends on two external libraries: the `Jinja2`_ template18+engine and the `Werkzeug`_ WSGI toolkit. both of which are not documented19+here. If you want to dive into their documentation check out the20+following links:21+22+- `Jinja2 Documentation <http://jinja.pocoo.org/2/documentation/>`_23+- `Werkzeug Documentation <http://werkzeug.pocoo.org/documentation/>`_24+25+.. _Jinja2: http://jinja.pocoo.org/2/26+.. _Werkzeug: http://werkzeug.pocoo.org/27+28+Textual Documentation29+---------------------30+31+This part of the documentation is written text and should give you an idea32+how to work with Flask. It's a series of step-by-step instructions for33+web development.34+35 .. toctree::36 :maxdepth: 237 38 foreword39 installation40 quickstart41 tutorial42+ testing43 patterns25- api44 deploying27- testing45 becomingbig46+47+Reference48+---------49+50+If you are looking for information on a specific function, class or51+method, this part of the documentation is for you:52+53+.. toctree::54+ :maxdepth: 255+56+ apimodified:docs/patterns.rst+183 added-6 removed
1 .. _patterns:2 3-Patterns in Flask4-=================3+Patterns for Flask4+==================5 6 Certain things are common enough that the changes are high you will find7 them in most web applications. For example quite a lot of applications8 are using relational databases and user authentication. In that case,9 changes are they will open a database connection at the beginning of the10 request and get the information of the currently logged in user. At the11 end of the request, the database connection is closed again.12 13-In Flask you can implement such things with the14-:meth:`~flask.Flask.before_request` and15-:meth:`~flask.Flask.after_request` decorators in combination with the16-special :class:`~flask.g` object.13 14+.. _larger-applications:15 16+Larger Applications17+-------------------18+19+For larger applications it's a good idea to use a package instead of a20+module. That is quite simple. Imagine a small application looks like21+this::22+23+ /yourapplication24+ /yourapplication.py25+ /static26+ /style.css27+ /templates28+ layout.html29+ index.html30+ login.html31+ ...32+33+To convert that into a larger one, just create a new folder34+`yourapplication` inside the existing one and move everything below it.35+Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete36+all `.pyc` files first, otherwise things would most likely break)37+38+You should then end up with something like that::39+40+ /yourapplication41+ /yourapplication42+ /__init__.py43+ /static44+ /style.css45+ /templates46+ layout.html47+ index.html48+ login.html49+ ...50+51+But how do you run your application now? The naive ``python52+yourapplication/__init__.py`` will not work. Let's just say that Python53+does not want modules in packages to be the startup file. But that is not54+a big problem, just add a new file called `runserver.py` next to the inner55+`yourapplication` folder with the following contents::56+57+ from yourapplication import app58+ app.run(debug=True)59+60+What did we gain from this? Now we can restructure the application a bit61+into multiple modules. The only thing you have to remember is the62+following quick checklist:63+64+1. 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.67+2. 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.71+72+Here an example `__init__.py`::73+74+ from flask import Flask75+ app = Flask(__name__)76+77+ import yourapplication.views78+79+And this is what `views.py` would look like::80+81+ from yourapplication import app82+83+ @app.route('/')84+ def index():85+ return 'Hello World!'86+87+.. admonition:: Circular Imports88+89+ 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.96+97+ 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.100+101+102 .. _database-pattern:103 104 Using SQLite 3 with Flask105 -------------------------106 107+In Flask you can implement opening of dabase connections at the beginning108+of the request and closing at the end with the109+:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`110+decorators in combination with the special :class:`~flask.g` object.111+112 So here a simple example how you can use SQLite 3 with Flask::113 114 import sqlite3115 from flask import g70 unmodified lines186 187 >>> from yourapplication import init_db188 >>> init_db()189 190+191+.. _sqlalchemy-pattern:192+193+SQLAlchemy in Flask194+-------------------195+196+Many people prefer `SQLAlchemy`_ for database access. In this case it's197+encouraged to use a package instead of a module for your flask application198+and drop the modules into a separate module (:ref:`larger-applications`).199+Although that is not necessary but makes a lot of sense.200+201+There are three very common ways to use SQLAlchemy. I will outline each202+of them here:203+204+Declarative205+```````````206+207+The declarative extension in SQLAlchemy is the most recent method of using208+SQLAlchemy. It allows you to define tables and models in one go, similar209+to how Django works. In addition to the following text I recommend the210+official documentation on the `declarative`_ extension.211+212+Here the example `database.py` module for your application::213+214+ from sqlalchemy import create_engine215+ from sqlalchemy.orm import scoped_session, sessionmaker216+ from sqlalchemy.ext.declarative import declarative_base217+218+ 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()224+225+ def init_db():226+ Base.metadata.create_all(bind=engine)227+228+To define your models, subclass the `Base` class the above code generated.229+230+To use SQLAlchemy in a declarative way with your application, you just231+have to put the following code into your application module Flask will232+automatically remove database sessions at the end of the request for you::233+234+ from yourapplication.database import db_session235+236+ @app.after_request237+ def shutdown_session(response):238+ db_session.remove()239+ return response240+241+Here an example model (put that into `models.py` for instance)::242+243+ from sqlalchemy import Column, Integer, String244+ from yourapplication.database import Base245+246+ 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)251+252+ def __init__(self, name=None, email=None):253+ self.name = name254+ self.email = email255+256+ def __repr__(self):257+ return '<User %r>' % (self.name, self.email)258+259+You can insert entries into the database like this then:260+261+>>> 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()266+267+Querying is simple as well:268+269+>>> User.query.all()270+[<User u'admin'>]271+>>> User.query.filter(User.name == 'admin').first()272+<User u'admin'>273+274+.. _SQLAlchemy: http://www.sqlalchemy.org/275+.. _declarative:276+ http://www.sqlalchemy.org/docs/reference/ext/declarative.html277+278+279 .. _template-inheritance:280 281 Template Inheritance282 --------------------147 unmodified lines