Flask Database Operations
In Flask, database operations are an important aspect of building web applications.
Flask provides multiple ways to interact with a database, including using raw SQL directly and using ORM (object-relational mapping) tools such as SQLAlchemy.
The following is a detailed explanation of Flask database operations, including basic operations with SQLAlchemy and direct execution of SQL statements.
- Using SQLAlchemy: Define models, configure the database, and perform basic CRUD operations.
- Creating and Managing Databases: When using
db.create_all()Create tables. - CRUD operations: Add, read, update, and delete records.
- Query Operations: Perform basic and complex queries, including sorting and pagination.
- Flask-Migrate: Manage database migrations with Flask-Migrate.
- Executing Raw SQL: Use raw SQL statements for database operations.
1. Using SQLAlchemy
SQLAlchemy is a powerful ORM library that simplifies database operations by interacting with database tables through Python objects.
Flask-SQLAlchemy is a Flask extension used to integrate SQLAlchemy.
Install Flask-SQLAlchemy
pip install flask-sqlalchemy
Configure SQLAlchemy
Code in app.py:
Example
from
flask
import
Flask
from
flask_sqlalchemy
import
SQLAlchemy
app
=
Flask
(
name
)
app.
config
[
'SQLALCHEMY_DATABASE_URI'
]
=
'sqlite:///example.db'
Using SQLite Database
app.
config
[
'SQLALCHEMY_TRACK_MODIFICATIONS'
]
=
False
db
=
SQLAlchemy
(
app
)
2. Define the model
Models are Python classes for database tables; each model class represents a table in the database.
Example
class
User
(
db.
Model
)
:
id
=
db.
Column
(
db.
Integer
,
primary_key
=
True
)
username
=
db.
Column
(
db.
String
(
80
)
,
unique
=
True
,
nullable
=
False
)
=
db.
Column
(
db.
String
(
120
)
,
unique
=
True
,
nullable
=
False
)
def
repr
(
self
)
:
return
f
'
db.Model: All model classes need to inherit from db.Model.
db.Column: Defines the fields of a model, specifying attributes such as the field type, whether it is a primary key, whether it is unique, and whether it can be null.
3. Creating and Managing Databases
Create Databases and Tables
After defining models, you can use the methods provided by SQLAlchemy to create databases and tables.
with app.app_context():
db.create_all()
db.create_all(): Creates tables corresponding to all models defined in the current context.
4. Basic CRUD Operations
Create Records
Example
@
app.
route
(
'/add_user'
)
def
add_user
(
)
:
new_user
=
User
(
username
=
'john_doe'
,
=
'john@example.com'
)
db.
session
.
add
(
new_user
)
db.
session
.
commit
(
)
return
'User added!'
db.session.add(new_user): Adds a new user object to the session.
db.session.commit(): Commits the transaction, saving changes to the database.
Read Records
Example
@
app.
route
(
'/get_users'
)
def
get_users
(
)
:
users
=
User.
query
.
all
(
)
Get All Users
return
'
'
.
join
(
[
f
'{user.username} ({user.email})'
for
user
in
users
]
)
User.query.all(): Queries all user records.
Updating Records
Example
@
app.
route
(
'/update_user/int:user_id'
)
def
update_user
(
user_id
)
:
user
=
User.
query
.
get
(
user_id
)
if
user
:
user
.
username
=
'new_username'
db.
session
.
commit
(
)
return
'User updated!'
return
'User not found!'
User.query.get(user_id): Queries a single user record by primary key.
Update field values and commit the transaction.
Delete records
Example
@
app.
route
(
'/delete_user/int:user_id'
)
def
delete_user
(
user_id
)
:
user
=
User.
query
.
get
(
user_id
)
if
user
:
db.
session
.
delete
(
user
)
db.
session
.
commit
(
)
return
'User deleted!'
return
'User not found!'
db.session.delete(user): Deletes a user record and commits the transaction.
5. Query Operations
SQLAlchemy provides rich query capabilities, allowing various query operations to be performed through query objects.
Basic Queries
users = User.query.filter_by(username='john_doe').all()
filter_by(): Filters records based on field values.
Complex Queries
from sqlalchemy import or_
users = User.query.filter(or_(User.username == 'john_doe', User.email == 'john@example.com')).all()
or_(): Used to construct complex query conditions.
Sorting and Pagination
users = User.query.order_by(User.username).paginate(page=1, per_page=10)
order_by(): Sorts by the specified field.
paginate(): Paginated queries.
6. Migrating with Flask-Migrate
Flask-Migrate is an extension for database migrations, based on Alembic, that helps you manage database version control.
Install Flask-Migrate
pip install flask-migrate
Configure Flask-Migrate
Code in app.py:
from flask_migrate import Migrate
migrate = Migrate(app, db)
Initialize Migrations
flask db init
Create Migration Scripts
flask db migrate -m "Initial migration."
Apply Migrations
flask db upgrade
flask db init: Initialize the migration environment.flask db migrate -m "message": Create migration scripts.flask db upgrade: Apply migrations to the database.
7. Executing Raw SQL
Although SQLAlchemy provides ORM functionality, you can also execute raw SQL statements.
Example
@
app.
route
(
'/raw_sql'
)
def
raw_sql
(
)
:
result
=
db.
session
.
execute
(
'SELECT * FROM user'
)
return
'
'
.
join
(
[
str
(
row
)
for
row
in
result
]
)
db.session.execute(): Executes raw SQL queries.
Connecting to and Operating a MySQL Database in Flask
Connecting to and operating a MySQL database in Flask usually involves using SQLAlchemy or directly using a MySQL Python driver. The following are detailed steps, including operations using Flask-SQLAlchemy and using a MySQL Python driver directly.
1. Connecting to MySQL with Flask-SQLAlchemy
Flask-SQLAlchemy is a Flask extension that simplifies SQLAlchemy configuration and operation. To connect to MySQL, you need to install Flask-SQLAlchemy and a MySQL driver.
Install the necessary libraries:
pip install flask-sqlalchemy mysqlclient
flask-sqlalchemy: Flask's SQLAlchemy extension.mysqlclient: A Python driver for the MySQL database.
Configure Flask-SQLAlchemy
Code in app.py:
Example
from
flask
import
Flask
from
flask_sqlalchemy
import
SQLAlchemy
app
=
Flask
(
name
)
app.
config
[
'SQLALCHEMY_DATABASE_URI'
]
=
'mysql://username:password@localhost/dbname'
app.
config
[
'SQLALCHEMY_TRACK_MODIFICATIONS'
]
=
False
db
=
SQLAlchemy
(
app
)
code>SQLALCHEMY_DATABASE_URI: Sets the database connection URI, in the format mysql://username:password@localhost/dbname。
username: MySQL username.password: MySQL password.localhost: MySQL host address (usually localhost for locallocalhost)。dbname: Database name.
Define Models and Perform Basic Operations
Code in app.py:
Example
class
User
(
db.
Model
)
:
id
=
db.
Column
(
db.
Integer
,
primary_key
=
True
)
username
=
db.
Column
(
db.
String
(
80
)
,
unique
=
True
,
nullable
=
False
)
=
db.
Column
(
db.
String
(
120
)
,
unique
=
True
,
nullable
=
False
)
def
repr
(
self
)
:
return
f
'
@
app.
route
(
'/'
)
def
index
(
)
:
users
=
User.
query
.
all
(
)
return
'
'
.
join
(
[
f
'{user.username} ({user.email})'
for
user
in
users
]
)
if
name
==
'main'
:
with
app.
app_context
(
)
:
db.
create_all
(
)
Creating a database table
app.
run
(
debug
=
True
)
Using a MySQL Python Driver Directly
If you choose not to use SQLAlchemy and instead use a MySQL Python driver directly, you can use the mysql-connector-python or PyMySQL library.
Install mysql-connector-python:
pip install mysql-connector-python
Install PyMySQL (if you choose to use PyMySQL):
pip install PyMySQL
Connect to MySQL Using mysql-connector-python
Code in app.py:
Example
from
flask
import
Flask
,
request
,
jsonify
import
mysql.
connector
app
=
Flask
(
name
)
def
get_db_connection
(
)
:
connection
=
mysql.
connector
.
connect
(
host
=
'localhost'
,
user
=
'username'
,
password
=
'password'
,
database
=
'dbname'
)
return
connection
@
app.
route
(
'/add_user'
,
methods
=
[
'POST'
]
)
def
add_user
(
)
:
data
=
request.
json
name
=
data
[
'name'
]
=
data
[
'email'
]
connection
=
get_db_connection
(
)
cursor
=
connection.
cursor
(
)
cursor.
execute
(
'INSERT INTO user (username, email) VALUES (%s, %s)'
,
(
name
,
)
)
connection.
commit
(
)
cursor.
close
(
)
connection.
close
(
)
return
'User added!'
@
app.
route
(
'/get_users'
)
def
get_users
(
)
:
connection
=
get_db_connection
(
)
cursor
=
connection.
cursor
(
dictionary
=
True
)
cursor.
execute
(
'SELECT * FROM user'
)
users
=
cursor.
fetchall
(
)
cursor.
close
(
)
connection.
close
(
)
return
jsonify
(
users
)
if
name
==
'main'
:
app.
run
(
debug
=
True
)
Connect to MySQL Using PyMySQL, code in app.py:
Example
from
flask
import
Flask
,
request
,
jsonify
import
pymysql
app
=
Flask
(
name
)
def
get_db_connection
(
)
:
connection
=
pymysql.
connect
(
host
=
'localhost'
,
user
=
'username'
,
password
=
'password'
,
database
=
'dbname'
,
cursorclass
=
pymysql.
cursors
.
DictCursor
)
return
connection
@
app.
route
(
'/add_user'
,
methods
=
[
'POST'
]
)
def
add_user
(
)
:
data
=
request.
json
name
=
data
[
'name'
]
=
data
[
'email'
]
connection
=
get_db_connection
(
)
with
connection.
cursor
(
)
as
cursor:
cursor.
execute
(
'INSERT INTO user (username, email) VALUES (%s, %s)'
,
(
name
,
)
)
connection.
commit
(
)
connection.
close
(
)
return
'User added!'
@
app.
route
(
'/get_users'
)
def
get_users
(
)
:
connection
=
get_db_connection
(
)
with
connection.
cursor
(
)
as
cursor:
cursor.
execute
(
'SELECT * FROM user'
)
users
=
cursor.
fetchall
(
)
connection.
close
(
)
return
jsonify
(
users
)
if
name
==
'main'
:
app.
run
(
debug
=
True
)