dbcon.rst
This file
The walk stopped after 200 commits: lines older than 8840973 point at it.
Fixed a cross reference in the docs.Armin Ronacherbefore adoption8840973
lines 1–57why, one step back1.. _tutorial-dbcon:23Step 4: Request Database Connections4------------------------------------56Now we know how we can open database connections and use them for scripts,7but how can we elegantly do that for requests? We will need the database8connection in all our functions so it makes sense to initialize them9before each request and shut them down afterwards.1011Flask allows us to do that with the :meth:`~flask.Flask.before_request`,12:meth:`~flask.Flask.after_request` and :meth:`~flask.Flask.teardown_request`13decorators::1415 @app.before_request16 def before_request():17 g.db = connect_db()1819 @app.teardown_request20 def teardown_request(exception):21 g.db.close()2223Functions marked with :meth:`~flask.Flask.before_request` are called before24a request and passed no arguments. Functions marked with25:meth:`~flask.Flask.after_request` are called after a request and26passed the response that will be sent to the client. They have to return27that response object or a different one. They are however not guaranteed28to be executed if an exception is raised, this is where functions marked with29:meth:`~flask.Flask.teardown_request` come in. They get called after the30response has been constructed. They are not allowed to modify the request, and31their return values are ignored. If an exception occurred while the request was32being processed, it is passed to each function; otherwise, `None` is passed in.3334We store our current database connection on the special :data:`~flask.g`35object that Flask provides for us. This object stores information for one36request only and is available from within each function. Never store such37things on other objects because this would not work with threaded38environments. That special :data:`~flask.g` object does some magic behind39the scenes to ensure it does the right thing.4041Continue to :ref:`tutorial-views`.4243.. hint:: Where do I put this code?4445 If you've been following along in this tutorial, you might be wondering46 where to put the code from this step and the next. A logical place is to47 group these module-level functions together, and put your new48 ``before_request`` and ``teardown_request`` functions below your existing49 ``init_db`` function (following the tutorial line-by-line).5051 If you need a moment to find your bearings, take a look at how the `example52 source`_ is organized. In Flask, you can put all of your application code53 into a single Python module. You don't have to, and if your app :ref:`grows54 larger <larger-applications>`, it's a good idea not to.5556.. _example source:57 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/