<h1>Define and Access the Database<aclass="headerlink"href="#define-and-access-the-database"title="Link to this heading">¶</a></h1>
<p>The application will use a <aclass="reference external"href="https://sqlite.org/about.html">SQLite</a> database to store users and posts.
Python comes with built-in support for SQLite in the <aclass="reference external"href="https://docs.python.org/3/library/sqlite3.html#module-sqlite3"title="(in Python v3.13)"><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">sqlite3</span></code></a>
module.</p>
<p>SQLite is convenient because it doesn’t require setting up a separate
database server and is built-in to Python. However, if concurrent
requests try to write to the database at the same time, they will slow
down as each write happens sequentially. Small applications won’t notice
this. Once you become big, you may want to switch to a different
database.</p>
<p>The tutorial doesn’t go into detail about SQL. If you are not familiar
with it, the SQLite docs describe the <aclass="reference external"href="https://sqlite.org/lang.html">language</a>.</p>
<sectionid="connect-to-the-database">
<h2>Connect to the Database<aclass="headerlink"href="#connect-to-the-database"title="Link to this heading">¶</a></h2>
<p>The first thing to do when working with a SQLite database (and most
other Python database libraries) is to create a connection to it. Any
queries and operations are performed using the connection, which is
closed after the work is finished.</p>
<p>In web applications this connection is typically tied to the request. It
is created at some point when handling a request, and closed before the
<divclass="code-block-caption"><spanclass="caption-text"><codeclass="docutils literal notranslate"><spanclass="pre">flaskr/db.py</span></code></span><aclass="headerlink"href="#id1"title="Link to this code">¶</a></div>
<p><aclass="reference internal"href="../api.html#flask.g"title="flask.g"><codeclass="xref py py-data docutils literal notranslate"><spanclass="pre">g</span></code></a> is a special object that is unique for each request. It is
used to store data that might be accessed by multiple functions during
the request. The connection is stored and reused instead of creating a
new connection if <codeclass="docutils literal notranslate"><spanclass="pre">get_db</span></code> is called a second time in the same
request.</p>
<p><aclass="reference internal"href="../api.html#flask.current_app"title="flask.current_app"><codeclass="xref py py-data docutils literal notranslate"><spanclass="pre">current_app</span></code></a> is another special object that points to the Flask
application handling the request. Since you used an application factory,
there is no application object when writing the rest of your code.
<codeclass="docutils literal notranslate"><spanclass="pre">get_db</span></code> will be called when the application has been created and is
handling a request, so <aclass="reference internal"href="../api.html#flask.current_app"title="flask.current_app"><codeclass="xref py py-data docutils literal notranslate"><spanclass="pre">current_app</span></code></a> can be used.</p>
<p><aclass="reference external"href="https://docs.python.org/3/library/sqlite3.html#sqlite3.connect"title="(in Python v3.13)"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">sqlite3.connect()</span></code></a> establishes a connection to the file pointed at
by the <codeclass="docutils literal notranslate"><spanclass="pre">DATABASE</span></code> configuration key. This file doesn’t have to exist
yet, and won’t until you initialize the database later.</p>
<p><aclass="reference external"href="https://docs.python.org/3/library/sqlite3.html#sqlite3.Row"title="(in Python v3.13)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">sqlite3.Row</span></code></a> tells the connection to return rows that behave
like dicts. This allows accessing the columns by name.</p>
<p><codeclass="docutils literal notranslate"><spanclass="pre">close_db</span></code> checks if a connection was created by checking if <codeclass="docutils literal notranslate"><spanclass="pre">g.db</span></code>
was set. If the connection exists, it is closed. Further down you will
tell your application about the <codeclass="docutils literal notranslate"><spanclass="pre">close_db</span></code> function in the application
factory so that it is called after each request.</p>
</section>
<sectionid="create-the-tables">
<h2>Create the Tables<aclass="headerlink"href="#create-the-tables"title="Link to this heading">¶</a></h2>
<p>In SQLite, data is stored in <em>tables</em> and <em>columns</em>. These need to be
created before you can store and retrieve data. Flaskr will store users
in the <codeclass="docutils literal notranslate"><spanclass="pre">user</span></code> table, and posts in the <codeclass="docutils literal notranslate"><spanclass="pre">post</span></code> table. Create a file
with the SQL commands needed to create empty tables:</p>
<divclass="code-block-caption"><spanclass="caption-text"><codeclass="docutils literal notranslate"><spanclass="pre">flaskr/schema.sql</span></code></span><aclass="headerlink"href="#id2"title="Link to this code">¶</a></div>
<divclass="code-block-caption"><spanclass="caption-text"><codeclass="docutils literal notranslate"><spanclass="pre">flaskr/db.py</span></code></span><aclass="headerlink"href="#id3"title="Link to this code">¶</a></div>
<spanclass="n">click</span><spanclass="o">.</span><spanclass="n">echo</span><spanclass="p">(</span><spanclass="s1">'Initialized the database.'</span><spanclass="p">)</span>
<p><aclass="reference internal"href="../api.html#flask.Flask.open_resource"title="flask.Flask.open_resource"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">open_resource()</span></code></a> opens a file relative to
the <codeclass="docutils literal notranslate"><spanclass="pre">flaskr</span></code> package, which is useful since you won’t necessarily know
where that location is when deploying the application later. <codeclass="docutils literal notranslate"><spanclass="pre">get_db</span></code>
returns a database connection, which is used to execute the commands
read from the file.</p>
<p><aclass="reference external"href="https://click.palletsprojects.com/en/stable/api/#click.command"title="(in Click v8.1.x)"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">click.command()</span></code></a> defines a command line command called <codeclass="docutils literal notranslate"><spanclass="pre">init-db</span></code>
that calls the <codeclass="docutils literal notranslate"><spanclass="pre">init_db</span></code> function and shows a success message to the
user. You can read <aclass="reference internal"href="../cli.html"><spanclass="doc">Command Line Interface</span></a> to learn more about writing commands.</p>
<p>The call to <aclass="reference external"href="https://docs.python.org/3/library/sqlite3.html#sqlite3.register_converter"title="(in Python v3.13)"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">sqlite3.register_converter()</span></code></a> tells Python how to
interpret timestamp values in the database. We convert the value to a
<h2>Register with the Application<aclass="headerlink"href="#register-with-the-application"title="Link to this heading">¶</a></h2>
<p>The <codeclass="docutils literal notranslate"><spanclass="pre">close_db</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">init_db_command</span></code> functions need to be registered
with the application instance; otherwise, they won’t be used by the
application. However, since you’re using a factory function, that
instance isn’t available when writing the functions. Instead, write a
function that takes an application and does the registration.</p>
<divclass="code-block-caption"><spanclass="caption-text"><codeclass="docutils literal notranslate"><spanclass="pre">flaskr/db.py</span></code></span><aclass="headerlink"href="#id4"title="Link to this code">¶</a></div>
<divclass="code-block-caption"><spanclass="caption-text"><codeclass="docutils literal notranslate"><spanclass="pre">flaskr/__init__.py</span></code></span><aclass="headerlink"href="#id5"title="Link to this code">¶</a></div>
<h2>Initialize the Database File<aclass="headerlink"href="#initialize-the-database-file"title="Link to this heading">¶</a></h2>
<p>Now that <codeclass="docutils literal notranslate"><spanclass="pre">init-db</span></code> has been registered with the app, it can be called
using the <codeclass="docutils literal notranslate"><spanclass="pre">flask</span></code> command, similar to the <codeclass="docutils literal notranslate"><spanclass="pre">run</span></code> command from the
previous page.</p>
<divclass="admonition note">
<pclass="admonition-title">Note</p>
<p>If you’re still running the server from the previous page, you can
either stop the server, or run this command in a new terminal. If
you use a new terminal, remember to change to your project directory
and activate the env as described in <aclass="reference internal"href="../installation.html"><spanclass="doc">Installation</span></a>.</p>
</div>
<p>Run the <codeclass="docutils literal notranslate"><spanclass="pre">init-db</span></code> command:</p>
<p>There will now be a <codeclass="docutils literal notranslate"><spanclass="pre">flaskr.sqlite</span></code> file in the <codeclass="docutils literal notranslate"><spanclass="pre">instance</span></code> folder in
your project.</p>
<p>Continue to <aclass="reference internal"href="views.html"><spanclass="doc">Blueprints and Views</span></a>.</p>