Define and Access the Database

    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.

    The tutorial doesn’t go into detail about SQL. If you are not familiar with it, the SQLite docs describe the language.

    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.

    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 response is sent.

    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 get_db is called a second time in the same request.

    current_app 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. get_db will be called when the application has been created and is handling a request, so can be used.

    sqlite3.connect() establishes a connection to the file pointed at by the DATABASE configuration key. This file doesn’t have to exist yet, and won’t until you initialize the database later.

    close_db checks if a connection was created by checking if g.db was set. If the connection exists, it is closed. Further down you will tell your application about the close_db function in the application factory so that it is called after each request.

    In SQLite, data is stored in tables and columns. These need to be created before you can store and retrieve data. Flaskr will store users in the user table, and posts in the post table. Create a file with the SQL commands needed to create empty tables:

    flaskr/schema.sql

    1. DROP TABLE IF EXISTS user;
    2. DROP TABLE IF EXISTS post;
    3. CREATE TABLE user (
    4. username TEXT UNIQUE NOT NULL,
    5. );
    6. CREATE TABLE post (
    7. id INTEGER PRIMARY KEY AUTOINCREMENT,
    8. author_id INTEGER NOT NULL,
    9. created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    10. body TEXT NOT NULL,
    11. FOREIGN KEY (author_id) REFERENCES user (id)
    12. );

    Add the Python functions that will run these SQL commands to the db.py file:

    flaskr/db.py

    opens a file relative to the flaskr package, which is useful since you won’t necessarily know where that location is when deploying the application later. get_db returns a database connection, which is used to execute the commands read from the file.

    click.command() defines a command line command called init-db that calls the function and shows a success message to the user. You can read to learn more about writing commands.

    The close_db and init_db_command 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.

    1. def init_app(app):
    2. app.teardown_appcontext(close_db)
    3. app.cli.add_command(init_db_command)

    app.teardown_appcontext() tells Flask to call that function when cleaning up after returning the response.

    adds a new command that can be called with the flask command.

    Import and call this function from the factory. Place the new code at the end of the factory function before returning the app.

    flaskr/__init__.py

    Now that init-db has been registered with the app, it can be called using the flask command, similar to the run command from the previous page.

    Note

    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 Installation.

    Run the init-db command:

    1. $ flask --app flaskr init-db
    2. Initialized the database.

    Continue to .