sqlite3 module.
Why SQLite?
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.
Connect to the Database
Create database connection function
Create Key concepts:
flaskr/db.py and add the database connection code:flaskr/db.py
gis a special object unique for each request, used to store data that might be accessed by multiple functionscurrent_apppoints to the Flask application handling the requestsqlite3.Rowtells the connection to return rows that behave like dicts, allowing column access by name
Create the database schema
In SQLite, data is stored in tables and columns. Create This creates two tables:
flaskr/schema.sql with the SQL commands to create empty tables:flaskr/schema.sql
usertable stores usernames and hashed passwordsposttable stores blog posts with a foreign key reference to the author
Add initialization functions
Add functions to run the SQL commands to
flaskr/db.py:flaskr/db.py
open_resource()opens a file relative to theflaskrpackageclick.commanddefines a command line command calledinit-dbregister_convertertells Python how to interpret timestamp values from the database
Register with the application
The
close_db and init_db_command functions need to be registered with the application instance. Add this function to flaskr/db.py:flaskr/db.py
app.teardown_appcontext()tells Flask to call that function when cleaning up after returning the responseapp.cli.add_command()adds a new command that can be called with theflaskcommand
Initialize the Database File
Now thatinit-db has been registered with the app, it can be called using the flask command:
flaskr.sqlite file in the instance folder in your project.
Complete Database Module
Here’s the completeflaskr/db.py file:
flaskr/db.py
