Skip to content
Myr

database.rst

This file

Path

docs/tutorial/database.rst

209 lines · 6.6 KiB

Last changed by

Merge pull request #4647 from pallets/cli-app_contextDavid Lordbefore adoptioncec5f74

History of this file

Take it

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

Merge pull request #4189 from mgu/feat/use-exclude-patterns-reloaderDavid Lordbefore adoption48ee204

lines 1–196why, 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 sqlite34041 import click42 from flask import current_app, g434445 def get_db():46 if 'db' not in g:47 g.db = sqlite3.connect(48 current_app.config['DATABASE'],49 detect_types=sqlite3.PARSE_DECLTYPES50 )51 g.db.row_factory = sqlite3.Row5253 return g.db545556 def close_db(e=None):57 db = g.pop('db', None)5859 if db is not None:60 db.close()6162:data:`g` is a special object that is unique for each request. It is63used to store data that might be accessed by multiple functions during64the request. The connection is stored and reused instead of creating a65new connection if ``get_db`` is called a second time in the same66request.6768:data:`current_app` is another special object that points to the Flask69application handling the request. Since you used an application factory,70there is no application object when writing the rest of your code.71``get_db`` will be called when the application has been created and is72handling a request, so :data:`current_app` can be used.7374:func:`sqlite3.connect` establishes a connection to the file pointed at75by the ``DATABASE`` configuration key. This file doesn't have to exist76yet, and won't until you initialize the database later.7778:class:`sqlite3.Row` tells the connection to return rows that behave79like dicts. This allows accessing the columns by name.8081``close_db`` checks if a connection was created by checking if ``g.db``82was set. If the connection exists, it is closed. Further down you will83tell your application about the ``close_db`` function in the application84factory so that it is called after each request.858687Create the Tables88-----------------8990In SQLite, data is stored in *tables* and *columns*. These need to be91created before you can store and retrieve data. Flaskr will store users92in the ``user`` table, and posts in the ``post`` table. Create a file93with the SQL commands needed to create empty tables:9495.. code-block:: sql96 :caption: ``flaskr/schema.sql``9798 DROP TABLE IF EXISTS user;99 DROP TABLE IF EXISTS post;100101 CREATE TABLE user (102 id INTEGER PRIMARY KEY AUTOINCREMENT,103 username TEXT UNIQUE NOT NULL,104 password TEXT NOT NULL105 );106107 CREATE TABLE post (108 id INTEGER PRIMARY KEY AUTOINCREMENT,109 author_id INTEGER NOT NULL,110 created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,111 title TEXT NOT NULL,112 body TEXT NOT NULL,113 FOREIGN KEY (author_id) REFERENCES user (id)114 );115116Add the Python functions that will run these SQL commands to the117``db.py`` file:118119.. code-block:: python120 :caption: ``flaskr/db.py``121122 def init_db():123 db = get_db()124125 with current_app.open_resource('schema.sql') as f:126 db.executescript(f.read().decode('utf8'))127128129 @click.command('init-db')130 def init_db_command():131 """Clear the existing data and create new tables."""132 init_db()133 click.echo('Initialized the database.')134135:meth:`open_resource() <Flask.open_resource>` opens a file relative to136the ``flaskr`` package, which is useful since you won't necessarily know137where that location is when deploying the application later. ``get_db``138returns a database connection, which is used to execute the commands139read from the file.140141:func:`click.command` defines a command line command called ``init-db``142that calls the ``init_db`` function and shows a success message to the143user. You can read :doc:`/cli` to learn more about writing commands.144145146Register with the Application147-----------------------------148149The ``close_db`` and ``init_db_command`` functions need to be registered150with the application instance; otherwise, they won't be used by the151application. However, since you're using a factory function, that152instance isn't available when writing the functions. Instead, write a153function that takes an application and does the registration.154155.. code-block:: python156 :caption: ``flaskr/db.py``157158 def init_app(app):159 app.teardown_appcontext(close_db)160 app.cli.add_command(init_db_command)161162:meth:`app.teardown_appcontext() <Flask.teardown_appcontext>` tells163Flask to call that function when cleaning up after returning the164response.165166:meth:`app.cli.add_command() <click.Group.add_command>` adds a new167command that can be called with the ``flask`` command.168169Import and call this function from the factory. Place the new code at170the end of the factory function before returning the app.171172.. code-block:: python173 :caption: ``flaskr/__init__.py``174175 def create_app():176 app = ...177 # existing code omitted178179 from . import db180 db.init_app(app)181182 return app183184185Initialize the Database File186----------------------------187188Now that ``init-db`` has been registered with the app, it can be called189using the ``flask`` command, similar to the ``run`` command from the190previous page.191192.. note::193194 If you're still running the server from the previous page, you can195 either stop the server, or run this command in a new terminal. If196 you use a new terminal, remember to change to your project directory

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 197why, one step back
197 and activate the env as described in :doc:`/installation`.

Merge pull request #4189 from mgu/feat/use-exclude-patterns-reloaderDavid Lordbefore adoption48ee204

lines 198–202why, one step back
198
199Run the ``init-db`` command:200201.. code-block:: none202

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 203why, one step back
203 $ flask --app flaskr init-db

Merge pull request #4189 from mgu/feat/use-exclude-patterns-reloaderDavid Lordbefore adoption48ee204

lines 204–209why, one step back
204 Initialized the database.
205206There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in207your project.208209Continue to :doc:`views`.