Skip to content
Myr

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

7 files+154 added−118 removed

modified:docs/tutorial/dbcon.rst+53 added-37 removed
1.. _tutorial-dbcon:23Step 4: Request Database Connections4------------------------------------3Step 3: 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.6We have created a function for establishing a database connection with7`create_db` but by itself that's not particularly useful. Creating and8closing database connections all the time is very inefficient, so we want9to keep it around for longer. Because database connections encapsulate a10transaction we also need to make sure that only one request at the time11uses the connection. So how can we elegantly do that with Flask?1211Flask 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::13This is where the application context comes into play. So let's start14there.1515 @app.before_request16 def before_request():17 g.db = connect_db()16Flask provides us with two contexts: the application context and the17request context. For the time being all you have to know is that there18are special variables that use these. For instance the19:data:`~flask.request` variable is the request object associated with20the current request, whereas :data:`~flask.g` is a general purpose21variable associated with the current application context. We will go into22the details of this a bit later.2319 @app.teardown_request20 def teardown_request(exception):21 db = getattr(g, 'db', None)22 if db is not None:23 db.close()24For the time being all you have to know is that you can store information25savely on the :data:`~flask.g` object.2625Functions marked with :meth:`~flask.Flask.before_request` are called before26a request and passed no arguments. Functions marked with27:meth:`~flask.Flask.after_request` are called after a request and28passed the response that will be sent to the client. They have to return29that response object or a different one. They are however not guaranteed30to be executed if an exception is raised, this is where functions marked with31:meth:`~flask.Flask.teardown_request` come in. They get called after the32response has been constructed. They are not allowed to modify the request, and33their return values are ignored. If an exception occurred while the request was34being processed, it is passed to each function; otherwise, `None` is passed in.27So when do you put it on there? To do that you can make a helper28function. The first time the function is called it will create a database29connection for the current context and successive calls will return the30already established connection::3136We store our current database connection on the special :data:`~flask.g`37object that Flask provides for us. This object stores information for one38request only and is available from within each function. Never store such39things on other objects because this would not work with threaded40environments. That special :data:`~flask.g` object does some magic behind41the 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_db3943For an even better way to handle such resources see the :ref:`sqlite3`44documentation.4046Continue to :ref:`tutorial-views`.41So now we know how to connect, but how do we properly disconnect? For42that flask provides us with the :meth:`~flask.Flask.teardown_appcontext`43decorator. It's executed every time the application context tears down::4445 @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()5051Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called52every time the app context tears down. So what does this mean?53Essentially the app context is created before the request comes in and is54destroyed (teared down) whenever the request finishes. A teardown can55happen because of two reasons: either everything went well (the error56parameter will be `None`) or an exception happend in which case the error57is passed to the teardown function.5859Curious about what these contexts mean? Have a look at the60:ref:`app-context` documentation to learn more.6162Continue to :ref:`tutorial-dbinit`.6364.. hint:: Where do I put this code?6566 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).7172 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 code
5 unmodified lines
modified:docs/tutorial/dbinit.rst+26 added-23 removed
1.. _tutorial-dbinit:23Step 3: Creating The Database3Step 4: Creating The Database4=============================56Flaskr is a database powered application as outlined earlier, and more7precisely, an application powered by a relational database system. Such
11 unmodified lines
19to provide the path to the database there which leaves some place for20errors. It's a good idea to add a function that initializes the database21for you to the application.2223If you want to do that, you first have to import the24:func:`contextlib.closing` function from the contextlib package.25Accordingly, add the following lines to your existing imports in `flaskr.py`::23To do this we can create a function called `init_db` that initializes the24database. Let me show you the code first. Just add that function below25the `connect_db` function in `flaskr.py`::2627 from contextlib import closing2829Next we can create a function called `init_db` that initializes the30database. For this we can use the `connect_db` function we defined31earlier. Just add that function below the `connect_db` function in32`flaskr.py`::3327 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()3340The :func:`~contextlib.closing` helper function allows us to keep a41connection open for the duration of the `with` block. The42:func:`~flask.Flask.open_resource` method of the application object43supports that functionality out of the box, so it can be used in the44`with` block directly. This function opens a file from the resource34So what's happening here? Remember how we learned last chapter that the35application context is created every time a request comes in? Here we36don't have a request yet, so we need to create the application context by37hand. Without an application context the :data:`~flask.g` object does not38know yet to which application it becomes as there could be more than one!3940The ``with app.app_context()`` statement establishes the application41context for us. In the body of the with statement the :flask:`~flask.g`42object will be associated with ``app``. At the end of the with statement43the association is released and all teardown functions are executed. This44means that our database connection is disconnected after the commit.4546The :func:`~flask.Flask.open_resource` method of the application object47is a convenient helper function that will open a resource that the48application provides. This function opens a file from the resource49location (your `flaskr` folder) and allows you to read from it. We are50using this here to execute a script on the database connection.5148When 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 to50execute a complete script. Finally we only have to commit the changes.51SQLite 3 and other transactional databases will not commit unless you52explicitly tell it to.52The connection object provided by SQLite can give us a cursor object.53On that cursor there is a method to execute a complete script. Finally we54only have to commit the changes. SQLite 3 and other transactional55databases will not commit unless you explicitly tell it to.5657Now it is possible to create a database by starting up a Python shell and58importing and calling that function::59
5 unmodified lines
65 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).6866Continue with :ref:`tutorial-dbcon`69Continue with :ref:`tutorial-views`
modified:docs/tutorial/index.rst+1 added-1 removed
22 unmodified lines
23 introduction24 folders25 schema26 setup27 dbinit27 dbcon28 dbinit29 views30 templates31 css32 testing
modified:docs/tutorial/setup.rst+41 added-29 removed
3 unmodified lines
4==============================56Now that we have the schema in place we can create the application module.7Let's call it `flaskr.py` inside the `flaskr` folder. For starters we8will add the imports we will need as well as the config section. For9small applications it's a possibility to drop the configuration directly10into the module which we will be doing here. However a cleaner solution11would be to create a separate `.ini` or `.py` file and load that or import12the values from there.8will add the imports and create the application object. For small9applications it's a possibility to drop the configuration directly into10the module which we will be doing here. However a cleaner solution would11be to create a separate `.ini` or `.py` file and load that or import the12values from there.1314In `flaskr.py`::14First we add the imports in `flaskr.py`::1516 # 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, flash2021 # configuration22 DATABASE = '/tmp/flaskr.db'23 DEBUG = True24 SECRET_KEY = 'development key'25 USERNAME = 'admin'26 PASSWORD = 'default'2728.. admonition:: Windows2930 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.3321Next we can create our actual application and initialize it with the22config from the same file, in `flaskr.py`::2324 # create our little application :)25 app = Flask(__name__)26 app.config.from_object(__name__)2741:meth:`~flask.Config.from_object` will look at the given object (if it's a42string it will import it) and then look for all uppercase variables43defined there. In our case, the configuration we just wrote a few lines44of 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)3738The :class:`~flask.Config` object works similar to a dictionary so we39can update it with new values.4041.. admonition:: Windows4243 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.4647Usually, it is a good idea to load a separate, environment specific48configuration file. Flask allows you to import multiple configurations and it 49will use the setting defined in the last import. This enables robust 50configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.
3 unmodified lines
54Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to 55a config file to be loaded. The silent switch just tells Flask to not complain 56if no such environment key is set.5758In addition to that you can use the :meth:`~flask.Config.from_object`59method on the config object and provide it with an import name of a60module. Flask will the initialize the variable from that module. Note61that in all cases only variable names that are uppercase are considered.6257The `secret_key` is needed to keep the client-side sessions secure.63The ``SECRET_KEY`` is needed to keep the client-side sessions secure.64Choose that key wisely and as hard to guess and complex as possible. The65debug flag enables or disables the interactive debugger. *Never leave66debug mode activated in a production system*, because it will allow users to67execute code on the server!6869We also add a method to easily connect to the database specified. That70can be used to open a connection on request and also from the interactive65Python shell or a script. This will come in handy later.71Python shell or a script. This will come in handy later. We create a72simple database connection through SQLite and then tell it to use the73:class:`sqlite3.Row` object to represent rows. This allows us to treat74the rows as if they were dictionaries instead of tuples.7576::7778 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 rv8384Finally we just add a line to the bottom of the file that fires up the85server if we want to run that file as a standalone application::86
17 unmodified lines
104 Want your server to be publicly available? Check out the105 :ref:`externally visible server <public-server>` section for more106 information.10796Continue with :ref:`tutorial-dbinit`.108Continue with :ref:`tutorial-dbcon`.
modified:docs/tutorial/views.rst+8 added-8 removed
10 unmodified lines
1112This view shows all the entries stored in the database. It listens on the13root of the application and will select title and text from the database.14The one with the highest id (the newest entry) will be on top. The rows15returned from the cursor are tuples with the columns ordered like specified16in the select statement. This is good enough for small applications like17here, but you might want to convert them into a dict. If you are18interested in how to do that, check out the :ref:`easy-querying` example.15returned from the cursor look a bit like tuples because we are using16the :class:`sqlite3.Row` row factory.1718The view function will pass the entries as dicts to the19`show_entries.html` template and return the rendered one::2021 @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)2728Add New Entry29-------------
7 unmodified lines
37 @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'))4748Note that we check that the user is logged in here (the `logged_in` key is
50 unmodified lines
modified:docs/index.rst+1 added
22 unmodified lines
2324- `Jinja2 Documentation <http://jinja.pocoo.org/2/documentation/>`_25- `Werkzeug Documentation <http://werkzeug.pocoo.org/documentation/>`_262728.. _Jinja2: http://jinja.pocoo.org/2/29.. _Werkzeug: http://werkzeug.pocoo.org/3031.. include:: contents.rst.inc
modified:examples/flaskr/flaskr.py+24 added-20 removed
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""1213from sqlite3 import dbapi2 as sqlite314from flask import Flask, request, session, redirect, url_for, abort, \15 render_template, flash, _app_ctx_stack14from flask import Flask, request, session, g, redirect, url_for, abort, \15 render_template, flash1617# configuration18DATABASE = '/tmp/flaskr.db'19DEBUG = True20SECRET_KEY = 'development key'21USERNAME = 'admin'22PASSWORD = 'default'1718# create our little application :)19app = Flask(__name__)26app.config.from_object(__name__)2021# Load default config and override config from an environment variable22app.config.update(dict(23 DATABASE='/tmp/flaskr.db',24 DEBUG=True,25 SECRET_KEY='development key',26 USERNAME='admin',27 PASSWORD='default'28))29app.config.from_envvar('FLASKR_SETTINGS', silent=True)303132def connect_db():33 """Connects to the specific database."""34 rv = sqlite3.connect(app.config['DATABASE'])35 rv.row_factory = sqlite3.Row36 return rv373839def init_db():40 """Creates the database tables."""41 with app.app_context():42 db = get_db()
5 unmodified lines
48def 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_db5549 return top.sqlite_db565157@app.teardown_appcontext53def close_db_connection(exception):58def 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()626364@app.route('/')65def show_entries():
43 unmodified lines