Skip to content
Myr

dbinit.rst

This file

Path

docs/tutorial/dbinit.rst

66 lines · 2.6 KiB

Last changed by

Merge branch 'sprint-branch'Armin Ronacherbefore adoption29e63e0

History of this file

Take it

1.. _tutorial-dbinit:23Step 3: Creating The Database4=============================56Flaskr is a database powered application as outlined earlier, and more7precisely, an application powered by a relational database system.  Such8systems need a schema that tells them how to store that information. So9before starting the server for the first time it's important to create10that schema.1112Such a schema can be created by piping the `schema.sql` file into the13`sqlite3` command as follows::1415    sqlite3 /tmp/flaskr.db < schema.sql1617The downside of this is that it requires the sqlite3 command to be18installed which is not necessarily the case on every system.  Also one has19to 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`::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`::3334    def init_db():35        with closing(connect_db()) as db:36            with app.open_resource('schema.sql', mode='r') as f:37                db.cursor().executescript(f.read())38            db.commit()3940The :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 resource45location (your `flaskr` folder) and allows you to read from it.  We are46using this here to execute a script on the database connection.4748When 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.5354Now it is possible to create a database by starting up a Python shell and55importing and calling that function::5657>>> from flaskr import init_db58>>> init_db()5960.. admonition:: Troubleshooting6162   If you get an exception later that a table cannot be found check that63   you did call the `init_db` function and that your table names are64   correct (singular vs. plural for example).6566Continue with :ref:`tutorial-dbcon`