Skip to content
Myr

database.rst

This file

Path

docs/tutorial/database.rst

219 lines · 6.9 KiB

Last changed by

merge app and request context (#5812)David Lordbefore adoptionadf3636

History of this file

Take it

The walk stopped after 200 commits: lines older than f822891 point at it.

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 1–39why, one step back
1.. currentmodule:: flask
23Define and Access the Database4==============================56The application will use a `SQLite`_ database to store users and posts.7Python comes with built-in support for SQLite in the :mod:`sqlite3`8module.910SQLite is convenient because it doesn't require setting up a separate11database server and is built-in to Python. However, if concurrent12requests try to write to the database at the same time, they will slow13down as each write happens sequentially. Small applications won't notice14this. Once you become big, you may want to switch to a different15database.1617The tutorial doesn't go into detail about SQL. If you are not familiar18with it, the SQLite docs describe the `language`_.1920.. _SQLite: https://sqlite.org/about.html21.. _language: https://sqlite.org/lang.html222324Connect to the Database25-----------------------2627The first thing to do when working with a SQLite database (and most28other Python database libraries) is to create a connection to it. Any29queries and operations are performed using the connection, which is30closed after the work is finished.3132In web applications this connection is typically tied to the request. It33is created at some point when handling a request, and closed before the34response is sent.3536.. code-block:: python37 :caption: ``flaskr/db.py``3839 import sqlite3

Merge remote-tracking branch 'origin/stable'David Lordbefore adoption22c48a7

line 40why, one step back
40 from datetime import datetime

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 41–62why, one step back
41
42 import click43 from flask import current_app, g444546 def get_db():47 if 'db' not in g:48 g.db = sqlite3.connect(49 current_app.config['DATABASE'],50 detect_types=sqlite3.PARSE_DECLTYPES51 )52 g.db.row_factory = sqlite3.Row5354 return g.db555657 def close_db(e=None):58 db = g.pop('db', None)5960 if db is not None:61 db.close()62

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 63why, one step back
63:data:`.g` is a special object that is unique for each request. It is

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 64–68why, one step back
64used to store data that might be accessed by multiple functions during
65the request. The connection is stored and reused instead of creating a66new connection if ``get_db`` is called a second time in the same67request.68

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 69why, one step back
69:data:`.current_app` is another special object that points to the Flask

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 70–72why, one step back
70application handling the request. Since you used an application factory,
71there is no application object when writing the rest of your code.72``get_db`` will be called when the application has been created and is

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 73why, one step back
73handling a request, so :data:`.current_app` can be used.

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 74–135why, one step back
74
75:func:`sqlite3.connect` establishes a connection to the file pointed at76by the ``DATABASE`` configuration key. This file doesn't have to exist77yet, and won't until you initialize the database later.7879:class:`sqlite3.Row` tells the connection to return rows that behave80like dicts. This allows accessing the columns by name.8182``close_db`` checks if a connection was created by checking if ``g.db``83was set. If the connection exists, it is closed. Further down you will84tell your application about the ``close_db`` function in the application85factory so that it is called after each request.868788Create the Tables89-----------------9091In SQLite, data is stored in *tables* and *columns*. These need to be92created before you can store and retrieve data. Flaskr will store users93in the ``user`` table, and posts in the ``post`` table. Create a file94with the SQL commands needed to create empty tables:9596.. code-block:: sql97 :caption: ``flaskr/schema.sql``9899 DROP TABLE IF EXISTS user;100 DROP TABLE IF EXISTS post;101102 CREATE TABLE user (103 id INTEGER PRIMARY KEY AUTOINCREMENT,104 username TEXT UNIQUE NOT NULL,105 password TEXT NOT NULL106 );107108 CREATE TABLE post (109 id INTEGER PRIMARY KEY AUTOINCREMENT,110 author_id INTEGER NOT NULL,111 created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,112 title TEXT NOT NULL,113 body TEXT NOT NULL,114 FOREIGN KEY (author_id) REFERENCES user (id)115 );116117Add the Python functions that will run these SQL commands to the118``db.py`` file:119120.. code-block:: python121 :caption: ``flaskr/db.py``122123 def init_db():124 db = get_db()125126 with current_app.open_resource('schema.sql') as f:127 db.executescript(f.read().decode('utf8'))128129130 @click.command('init-db')131 def init_db_command():132 """Clear the existing data and create new tables."""133 init_db()134 click.echo('Initialized the database.')135

Merge remote-tracking branch 'origin/stable'David Lordbefore adoption22c48a7

lines 136–140why, one step back
136
137 sqlite3.register_converter(138 "timestamp", lambda v: datetime.fromisoformat(v.decode())139 )140

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 141–149why, one step back
141:meth:`open_resource() <Flask.open_resource>` opens a file relative to
142the ``flaskr`` package, which is useful since you won't necessarily know143where that location is when deploying the application later. ``get_db``144returns a database connection, which is used to execute the commands145read from the file.146147:func:`click.command` defines a command line command called ``init-db``148that calls the ``init_db`` function and shows a success message to the149user. You can read :doc:`/cli` to learn more about writing commands.

Merge remote-tracking branch 'origin/stable'David Lordbefore adoption22c48a7

lines 150–153why, one step back
150
151The call to :func:`sqlite3.register_converter` tells Python how to152interpret timestamp values in the database. We convert the value to a153:class:`datetime.datetime`.

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 154–219why, one step back
154
155156Register with the Application157-----------------------------158159The ``close_db`` and ``init_db_command`` functions need to be registered160with the application instance; otherwise, they won't be used by the161application. However, since you're using a factory function, that162instance isn't available when writing the functions. Instead, write a163function that takes an application and does the registration.164165.. code-block:: python166 :caption: ``flaskr/db.py``167168 def init_app(app):169 app.teardown_appcontext(close_db)170 app.cli.add_command(init_db_command)171172:meth:`app.teardown_appcontext() <Flask.teardown_appcontext>` tells173Flask to call that function when cleaning up after returning the174response.175176:meth:`app.cli.add_command() <click.Group.add_command>` adds a new177command that can be called with the ``flask`` command.178179Import and call this function from the factory. Place the new code at180the end of the factory function before returning the app.181182.. code-block:: python183 :caption: ``flaskr/__init__.py``184185 def create_app():186 app = ...187 # existing code omitted188189 from . import db190 db.init_app(app)191192 return app193194195Initialize the Database File196----------------------------197198Now that ``init-db`` has been registered with the app, it can be called199using the ``flask`` command, similar to the ``run`` command from the200previous page.201202.. note::203204 If you're still running the server from the previous page, you can205 either stop the server, or run this command in a new terminal. If206 you use a new terminal, remember to change to your project directory207 and activate the env as described in :doc:`/installation`.208209Run the ``init-db`` command:210211.. code-block:: none212213 $ flask --app flaskr init-db214 Initialized the database.215216There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in217your project.218219Continue to :doc:`views`.