database.rst
This file
Path
docs/tutorial/database.rst
213 lines · 6.7 KiB
Last changed by
remove unused ref directivesDavid Lordbefore adoption171aabc
History of this fileTake it
The walk stopped after 200 commits: lines older than cae0378 point at it.
Merge pull request #2786 from greyli/patch-9Hsiaoming Yangbefore adoptioncae0378
lines 1–144why, one step back1.. currentmodule:: flask23Define 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, g43 from flask.cli import with_appcontext444546 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()6263:data:`g` is a special object that is unique for each request. It is64used to store data that might be accessed by multiple functions during65the request. The connection is stored and reused instead of creating a66new connection if ``get_db`` is called a second time in the same67request.6869:data:`current_app` is another special object that points to the Flask70application 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 is73handling a request, so :data:`current_app` can be used.7475: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 @with_appcontext132 def init_db_command():133 """Clear the existing data and create new tables."""134 init_db()135 click.echo('Initialized the database.')136137:meth:`open_resource() <Flask.open_resource>` opens a file relative to138the ``flaskr`` package, which is useful since you won't necessarily know139where that location is when deploying the application later. ``get_db``140returns a database connection, which is used to execute the commands141read from the file.142143:func:`click.command` defines a command line command called ``init-db``144that calls the ``init_db`` function and shows a success message to theremove unused ref directivesDavid Lordbefore adoption171aabc
line 145why, one step back145user. You can read :doc:`/cli` to learn more about writing commands.Merge pull request #2786 from greyli/patch-9Hsiaoming Yangbefore adoptioncae0378
lines 146–151why, one step back146147148Register with the Application149-----------------------------150151The ``close_db`` and ``init_db_command`` functions need to be registeredMerge branch '1.0-maintenance'David Lordbefore adoption3b45b82
line 152why, one step back152with the application instance; otherwise, they won't be used by theMerge pull request #2786 from greyli/patch-9Hsiaoming Yangbefore adoptioncae0378
lines 153–198why, one step back153application. However, since you're using a factory function, that154instance isn't available when writing the functions. Instead, write a155function that takes an application and does the registration.156157.. code-block:: python158 :caption: ``flaskr/db.py``159160 def init_app(app):161 app.teardown_appcontext(close_db)162 app.cli.add_command(init_db_command)163164:meth:`app.teardown_appcontext() <Flask.teardown_appcontext>` tells165Flask to call that function when cleaning up after returning the166response.167168:meth:`app.cli.add_command() <click.Group.add_command>` adds a new169command that can be called with the ``flask`` command.170171Import and call this function from the factory. Place the new code at172the end of the factory function before returning the app.173174.. code-block:: python175 :caption: ``flaskr/__init__.py``176177 def create_app():178 app = ...179 # existing code omitted180181 from . import db182 db.init_app(app)183184 return app185186187Initialize the Database File188----------------------------189190Now that ``init-db`` has been registered with the app, it can be called191using the ``flask`` command, similar to the ``run`` command from the192previous page.193194.. note::195196 If you're still running the server from the previous page, you can197 either stop the server, or run this command in a new terminal. If198 you use a new terminal, remember to change to your project directoryremove unused ref directivesDavid Lordbefore adoption171aabc
lines 199–201why, one step back199 and activate the env as described in :doc:`/installation`. You'll200 also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on the201 previous page.Merge pull request #2786 from greyli/patch-9Hsiaoming Yangbefore adoptioncae0378
lines 202–206why, one step back202203Run the ``init-db`` command:204205.. code-block:: none206Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 207why, one step back207 $ flask init-dbMerge pull request #2786 from greyli/patch-9Hsiaoming Yangbefore adoptioncae0378
lines 208–213why, one step back208 Initialized the database.209210There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in211your project.212213Continue to :doc:`views`.