dbinit.rst
This file
Path
docs/tutorial/dbinit.rst
57 lines · 2.4 KiB
Last changed by
New style for the documentation. Looks more like the website now.Armin Ronacherbefore adoptionbcf347f
History of this fileTake it
1Step 3: Creating The Database2=============================34Flaskr is a database powered application as outlined earlier, and more5precisely, an application powered by a relational database system. Such6systems need a schema that tells them how to store that information. So7before starting the server for the first time it's important to create8that schema.910Such a schema can be created by piping the `schema.sql` file into the11`sqlite3` command as follows::1213 sqlite3 /tmp/flaskr.db < schema.sql1415The downside of this is that it requires the sqlite3 command to be16installed which is not necessarily the case on every system. Also one has17to provide the path to the database there which leaves some place for18errors. It's a good idea to add a function that initializes the database19for you to the application.2021If you want to do that, you first have to import the22:func:`contextlib.closing` function from the contextlib package. If you23want to use Python 2.5 it's also necessary to enable the `with` statement24first (`__future__` imports must be the very first import)::2526 from __future__ import with_statement27 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::32 33 def init_db():34 with closing(connect_db()) as db:35 with app.open_resource('schema.sql') as f:36 db.cursor().executescript(f.read())37 db.commit()3839The :func:`~contextlib.closing` helper function allows us to keep a40connection open for the duration of the `with` block. The41:func:`~flask.Flask.open_resource` method of the application object42supports that functionality out of the box, so it can be used in the43`with` block directly. This function opens a file from the resource44location (your `flaskr` folder) and allows you to read from it. We are45using this here to execute a script on the database connection.4647When we connect to a database we get a connection object (here called48`db`) that can give us a cursor. On that cursor there is a method to49execute a complete script. Finally we only have to commit the changes.50SQLite 3 and other transactional databases will not commit unless you51explicitly tell it to.5253Now it is possible to create a database by starting up a Python shell and54importing and calling that function::5556>>> from flaskr import init_db57>>> init_db()