Rewrote tutorial to use the g based appcontext object
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 42cf782 · Browse files · 7 files·+154 added−118 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+154 added−118 removed
- other:+154 added−118 removed
Provenance
- Commit
05161d3- Tree
0d91faf- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
42cf782
7 files changed+154 added−118 removed
modified:docs/tutorial/dbcon.rst+53 added-37 removed
1 .. _tutorial-dbcon:2 3-Step 4: Request Database Connections4-------------------------------------3+Step 3: Database Connections4+----------------------------5 6-Now we know how we can open database connections and use them for scripts,7-but how can we elegantly do that for requests? We will need the database8-connection in all our functions so it makes sense to initialize them9-before each request and shut them down afterwards.6+We have created a function for establishing a database connection with7+`create_db` but by itself that's not particularly useful. Creating and8+closing database connections all the time is very inefficient, so we want9+to keep it around for longer. Because database connections encapsulate a10+transaction we also need to make sure that only one request at the time11+uses the connection. So how can we elegantly do that with Flask?12 11-Flask allows us to do that with the :meth:`~flask.Flask.before_request`,12-:meth:`~flask.Flask.after_request` and :meth:`~flask.Flask.teardown_request`13-decorators::13+This is where the application context comes into play. So let's start14+there.15 15- @app.before_request16- def before_request():17- g.db = connect_db()16+Flask provides us with two contexts: the application context and the17+request context. For the time being all you have to know is that there18+are special variables that use these. For instance the19+:data:`~flask.request` variable is the request object associated with20+the current request, whereas :data:`~flask.g` is a general purpose21+variable associated with the current application context. We will go into22+the details of this a bit later.23 19- @app.teardown_request20- def teardown_request(exception):21- db = getattr(g, 'db', None)22- if db is not None:23- db.close()24+For the time being all you have to know is that you can store information25+savely on the :data:`~flask.g` object.26 25-Functions marked with :meth:`~flask.Flask.before_request` are called before26-a request and passed no arguments. Functions marked with27-:meth:`~flask.Flask.after_request` are called after a request and28-passed the response that will be sent to the client. They have to return29-that response object or a different one. They are however not guaranteed30-to be executed if an exception is raised, this is where functions marked with31-:meth:`~flask.Flask.teardown_request` come in. They get called after the32-response has been constructed. They are not allowed to modify the request, and33-their return values are ignored. If an exception occurred while the request was34-being processed, it is passed to each function; otherwise, `None` is passed in.27+So when do you put it on there? To do that you can make a helper28+function. The first time the function is called it will create a database29+connection for the current context and successive calls will return the30+already established connection::31 36-We store our current database connection on the special :data:`~flask.g`37-object that Flask provides for us. This object stores information for one38-request only and is available from within each function. Never store such39-things on other objects because this would not work with threaded40-environments. That special :data:`~flask.g` object does some magic behind41-the scenes to ensure it does the right thing.32+ def get_db():33+ """Opens a new database connection if there is none yet for the34+ current application context.35+ """36+ if not hasattr(g, 'sqlite_db'):37+ g.sqlite_db = connect_db()38+ return g.sqlite_db39 43-For an even better way to handle such resources see the :ref:`sqlite3`44-documentation.40 46-Continue to :ref:`tutorial-views`.41+So now we know how to connect, but how do we properly disconnect? For42+that flask provides us with the :meth:`~flask.Flask.teardown_appcontext`43+decorator. It's executed every time the application context tears down::44 45+ @app.teardown_appcontext46+ def close_db(error):47+ """Closes the database again at the end of the request."""48+ if hasattr(g, 'sqlite_db'):49+ g.sqlite_db.close()50+51+Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called52+every time the app context tears down. So what does this mean?53+Essentially the app context is created before the request comes in and is54+destroyed (teared down) whenever the request finishes. A teardown can55+happen because of two reasons: either everything went well (the error56+parameter will be `None`) or an exception happend in which case the error57+is passed to the teardown function.58+59+Curious about what these contexts mean? Have a look at the60+:ref:`app-context` documentation to learn more.61+62+Continue to :ref:`tutorial-dbinit`.63+64 .. hint:: Where do I put this code?65 66 If you've been following along in this tutorial, you might be wondering67 where to put the code from this step and the next. A logical place is to68 group these module-level functions together, and put your new53- ``before_request`` and ``teardown_request`` functions below your existing69+ ``get_db`` and ``close_db`` functions below your existing70 ``init_db`` function (following the tutorial line-by-line).71 72 If you need a moment to find your bearings, take a look at how the `example73 source`_ is organized. In Flask, you can put all of your application code5 unmodified linesmodified:docs/tutorial/dbinit.rst+26 added-23 removed
1 .. _tutorial-dbinit:2 3-Step 3: Creating The Database3+Step 4: Creating The Database4 =============================5 6 Flaskr is a database powered application as outlined earlier, and more7 precisely, an application powered by a relational database system. Such11 unmodified lines19 to provide the path to the database there which leaves some place for20 errors. It's a good idea to add a function that initializes the database21 for you to the application.22 23-If you want to do that, you first have to import the24-:func:`contextlib.closing` function from the contextlib package.25-Accordingly, add the following lines to your existing imports in `flaskr.py`::23+To do this we can create a function called `init_db` that initializes the24+database. Let me show you the code first. Just add that function below25+the `connect_db` function in `flaskr.py`::26 27- from contextlib import closing28-29-Next we can create a function called `init_db` that initializes the30-database. For this we can use the `connect_db` function we defined31-earlier. Just add that function below the `connect_db` function in32-`flaskr.py`::33-27 def init_db():35- with closing(connect_db()) as db:28+ app app.app_context():29+ db = get_db()30 with app.open_resource('schema.sql', mode='r') as f:31 db.cursor().executescript(f.read())32 db.commit()33 40-The :func:`~contextlib.closing` helper function allows us to keep a41-connection open for the duration of the `with` block. The42-:func:`~flask.Flask.open_resource` method of the application object43-supports that functionality out of the box, so it can be used in the44-`with` block directly. This function opens a file from the resource34+So what's happening here? Remember how we learned last chapter that the35+application context is created every time a request comes in? Here we36+don't have a request yet, so we need to create the application context by37+hand. Without an application context the :data:`~flask.g` object does not38+know yet to which application it becomes as there could be more than one!39+40+The ``with app.app_context()`` statement establishes the application41+context for us. In the body of the with statement the :flask:`~flask.g`42+object will be associated with ``app``. At the end of the with statement43+the association is released and all teardown functions are executed. This44+means that our database connection is disconnected after the commit.45+46+The :func:`~flask.Flask.open_resource` method of the application object47+is a convenient helper function that will open a resource that the48+application provides. This function opens a file from the resource49 location (your `flaskr` folder) and allows you to read from it. We are50 using this here to execute a script on the database connection.51 48-When we connect to a database we get a connection object (here called49-`db`) that can give us a cursor. On that cursor there is a method to50-execute a complete script. Finally we only have to commit the changes.51-SQLite 3 and other transactional databases will not commit unless you52-explicitly tell it to.52+The connection object provided by SQLite can give us a cursor object.53+On that cursor there is a method to execute a complete script. Finally we54+only have to commit the changes. SQLite 3 and other transactional55+databases will not commit unless you explicitly tell it to.56 57 Now it is possible to create a database by starting up a Python shell and58 importing and calling that function::59 5 unmodified lines65 If you get an exception later that a table cannot be found check that66 you did call the `init_db` function and that your table names are67 correct (singular vs. plural for example).68 66-Continue with :ref:`tutorial-dbcon`69+Continue with :ref:`tutorial-views`modified:docs/tutorial/index.rst+1 added-1 removed
22 unmodified lines23 introduction24 folders25 schema26 setup27- dbinit27 dbcon28+ dbinit29 views30 templates31 css32 testingmodified:docs/tutorial/setup.rst+41 added-29 removed
3 unmodified lines4 ==============================5 6 Now that we have the schema in place we can create the application module.7 Let's call it `flaskr.py` inside the `flaskr` folder. For starters we8-will add the imports we will need as well as the config section. For9-small applications it's a possibility to drop the configuration directly10-into the module which we will be doing here. However a cleaner solution11-would be to create a separate `.ini` or `.py` file and load that or import12-the values from there.8+will add the imports and create the application object. For small9+applications it's a possibility to drop the configuration directly into10+the module which we will be doing here. However a cleaner solution would11+be to create a separate `.ini` or `.py` file and load that or import the12+values from there.13 14-In `flaskr.py`::14+First we add the imports in `flaskr.py`::15 16 # all the imports17 import sqlite318- from flask import Flask, request, session, g, redirect, url_for, \19- abort, render_template, flash18+ from flask import Flask, request, session, g, redirect, url_for, abort, \19+ render_template, flash20 21- # configuration22- DATABASE = '/tmp/flaskr.db'23- DEBUG = True24- SECRET_KEY = 'development key'25- USERNAME = 'admin'26- PASSWORD = 'default'27-28-.. admonition:: Windows29-30- If you are on Windows, replace `/tmp/flaskr.db` with a different writeable31- path of your choice, in the configuration and for the rest of this32- tutorial.33-21 Next we can create our actual application and initialize it with the22 config from the same file, in `flaskr.py`::23 24 # create our little application :)25 app = Flask(__name__)26 app.config.from_object(__name__)27 41-:meth:`~flask.Config.from_object` will look at the given object (if it's a42-string it will import it) and then look for all uppercase variables43-defined there. In our case, the configuration we just wrote a few lines44-of code above. You can also move that into a separate file.28+ # Load default config and override config from an environment variable29+ app.config.update(dict(30+ DATABASE='/tmp/flaskr.db',31+ DEBUG=True,32+ SECRET_KEY='development key',33+ USERNAME='admin',34+ PASSWORD='default'35+ ))36+ app.config.from_envvar('FLASKR_SETTINGS', silent=True)37 38+The :class:`~flask.Config` object works similar to a dictionary so we39+can update it with new values.40+41+.. admonition:: Windows42+43+ If you are on Windows, replace `/tmp/flaskr.db` with a different writeable44+ path of your choice, in the configuration and for the rest of this45+ tutorial.46+47 Usually, it is a good idea to load a separate, environment specific48 configuration file. Flask allows you to import multiple configurations and it 49 will use the setting defined in the last import. This enables robust 50 configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this. 3 unmodified lines54 Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to 55 a config file to be loaded. The silent switch just tells Flask to not complain 56 if no such environment key is set.57 58+In addition to that you can use the :meth:`~flask.Config.from_object`59+method on the config object and provide it with an import name of a60+module. Flask will the initialize the variable from that module. Note61+that in all cases only variable names that are uppercase are considered.62+57-The `secret_key` is needed to keep the client-side sessions secure.63+The ``SECRET_KEY`` is needed to keep the client-side sessions secure.64 Choose that key wisely and as hard to guess and complex as possible. The65 debug flag enables or disables the interactive debugger. *Never leave66 debug mode activated in a production system*, because it will allow users to67 execute code on the server!68 69 We also add a method to easily connect to the database specified. That70 can be used to open a connection on request and also from the interactive65-Python shell or a script. This will come in handy later.71+Python shell or a script. This will come in handy later. We create a72+simple database connection through SQLite and then tell it to use the73+:class:`sqlite3.Row` object to represent rows. This allows us to treat74+the rows as if they were dictionaries instead of tuples.75 76 ::77 78 def connect_db():79+ """Connects to the specific database."""70- return sqlite3.connect(app.config['DATABASE'])80+ rv = sqlite3.connect(app.config['DATABASE'])81+ rv.row_factory = sqlite3.Row82+ return rv83 84 Finally we just add a line to the bottom of the file that fires up the85 server if we want to run that file as a standalone application::86 17 unmodified lines104 Want your server to be publicly available? Check out the105 :ref:`externally visible server <public-server>` section for more106 information.107 96-Continue with :ref:`tutorial-dbinit`.108+Continue with :ref:`tutorial-dbcon`.modified:docs/tutorial/views.rst+8 added-8 removed
10 unmodified lines11 12 This view shows all the entries stored in the database. It listens on the13 root of the application and will select title and text from the database.14 The one with the highest id (the newest entry) will be on top. The rows15-returned from the cursor are tuples with the columns ordered like specified16-in the select statement. This is good enough for small applications like17-here, but you might want to convert them into a dict. If you are18-interested in how to do that, check out the :ref:`easy-querying` example.15+returned from the cursor look a bit like tuples because we are using16+the :class:`sqlite3.Row` row factory.17 18 The view function will pass the entries as dicts to the19 `show_entries.html` template and return the rendered one::20 21 @app.route('/')22 def show_entries():23+ db = get_db()25- cur = g.db.execute('select title, text from entries order by id desc')26- entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]24+ cur = db.execute('select title, text from entries order by id desc')25+ entries = cur.fetchall()26 return render_template('show_entries.html', entries=entries)27 28 Add New Entry29 -------------7 unmodified lines37 @app.route('/add', methods=['POST'])38 def add_entry():39 if not session.get('logged_in'):40 abort(401)41+ db = get_db()42- g.db.execute('insert into entries (title, text) values (?, ?)',42+ db.execute('insert into entries (title, text) values (?, ?)',43 [request.form['title'], request.form['text']])44- g.db.commit()44+ db.commit()45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))47 48 Note that we check that the user is logged in here (the `logged_in` key is50 unmodified linesmodified:docs/index.rst+1 added
22 unmodified lines23 24 - `Jinja2 Documentation <http://jinja.pocoo.org/2/documentation/>`_25 - `Werkzeug Documentation <http://werkzeug.pocoo.org/documentation/>`_26 27+28 .. _Jinja2: http://jinja.pocoo.org/2/29 .. _Werkzeug: http://werkzeug.pocoo.org/30 31 .. include:: contents.rst.incmodified:examples/flaskr/flaskr.py+24 added-20 removed
9 unmodified lines10 :license: BSD, see LICENSE for more details.11 """12 13 from sqlite3 import dbapi2 as sqlite314-from flask import Flask, request, session, redirect, url_for, abort, \15- render_template, flash, _app_ctx_stack14+from flask import Flask, request, session, g, redirect, url_for, abort, \15+ render_template, flash16 17-# configuration18-DATABASE = '/tmp/flaskr.db'19-DEBUG = True20-SECRET_KEY = 'development key'21-USERNAME = 'admin'22-PASSWORD = 'default'17 18 # create our little application :)19 app = Flask(__name__)26-app.config.from_object(__name__)20+21+# Load default config and override config from an environment variable22+app.config.update(dict(23+ DATABASE='/tmp/flaskr.db',24+ DEBUG=True,25+ SECRET_KEY='development key',26+ USERNAME='admin',27+ PASSWORD='default'28+))29 app.config.from_envvar('FLASKR_SETTINGS', silent=True)30 31 32+def connect_db():33+ """Connects to the specific database."""34+ rv = sqlite3.connect(app.config['DATABASE'])35+ rv.row_factory = sqlite3.Row36+ return rv37+38+39 def init_db():40 """Creates the database tables."""41 with app.app_context():42 db = get_db()5 unmodified lines48 def get_db():49 """Opens a new database connection if there is none yet for the50 current application context.51 """43- top = _app_ctx_stack.top44- if not hasattr(top, 'sqlite_db'):45- sqlite_db = sqlite3.connect(app.config['DATABASE'])46- sqlite_db.row_factory = sqlite3.Row47- top.sqlite_db = sqlite_db52+ if not hasattr(g, 'sqlite_db'):53+ g.sqlite_db = connect_db()54+ return g.sqlite_db55 49- return top.sqlite_db56 51-57 @app.teardown_appcontext53-def close_db_connection(exception):58+def close_db(error):59 """Closes the database again at the end of the request."""55- top = _app_ctx_stack.top56- if hasattr(top, 'sqlite_db'):57- top.sqlite_db.close()60+ if hasattr(g, 'sqlite_db'):61+ g.sqlite_db.close()62 63 64 @app.route('/')65 def show_entries():43 unmodified lines