Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Database Integration

Flask Database Integration

Most web applications need to store data persistently.

This chapter uses Python's built-in SQLite database to show how to integrate a database in Flask without installing additional dependencies.


SQLite quick start

SQLite is a lightweight database that stores data in a single file, with support built into the Python standard library.

It is the best choice for learning and prototyping—no database server installation and no configuration needed.

Example

A simple SQLite example (without Flask)

import

sqlite3

Connect to the database (automatically created if runoob.db does not exist)

conn

=

sqlite3.

connect

(

"runoob.db"

)

row_factory lets query results be accessed by field name like a dict

conn.

row_factory

=

sqlite3.

Row

Create a table

conn.

execute

(

"CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, username TEXT UNIQUE, password TEXT)"

)

Insert data

conn.

execute

(

"INSERT INTO user (username, password) VALUES (?, ?)"

,

(

"runoob"

,

"pass123"

)

)

conn.

commit

(

)

Query data

rows

=

conn.

execute

(

"SELECT * FROM user"

)

.

fetchall

(

)

for

row

in

rows:

   

print

(

dict

(

row

)

)

 

Output: {'id': 1, 'username': 'runoob', 'password': 'pass123'}

conn.

close

(

)


Managing database connections with the g object in Flask

g is a special object whose lifetime is a single request.

Storing the database connection in g ensures that multiple database operations within the same request share the same connection, which is cleaned up automatically when the request ends.

Example

File path: db.py (database management module)

import

sqlite3

from

flask

import

g

,

current_app

def

get_db

(

)

:

   

"""Get the database connection, reused within the same request"""

   

if

"db"

not

in

g:

       

Read the database path from the configuration

        db_path

=

current_app.

config

.

get

(

"DATABASE"

,

"runoob.db"

)

        g.

db

=

sqlite3.

connect

(

db_path

)

        g.

db

.

row_factory

=

sqlite3.

Row

 

Let results support field-name access

   

return

g.

db

def

close_db

(

error

=

None

)

:

   

"""Close the database connection (called automatically when the request ends)"""

    db

=

g.

pop

(

"db"

,

None

)

   

if

db

is

not

None

:

        db.

close

(

)

def

init_db

(

)

:

   

"""Initialize the database table structure"""

    db

=

get_db

(

)

    db.

execute

(

"""
        CREATE TABLE IF NOT EXISTS user (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    """

)

    db.

execute

(

"""
        CREATE TABLE IF NOT EXISTS post (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            body TEXT NOT NULL,
            author_id INTEGER NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (author_id) REFERENCES user (id)
        )
    """

)

    db.

commit

(

)

def

init_app

(

app

)

:

   

"""Register database-related functionality in the Flask application"""

   

Automatically close the database connection when the request ends

    app.

teardown_appcontext

(

close_db

)

   

Register a CLI command: flask init-db

    app.

cli

.

command

(

"init-db"

)

(

init_db

)


Integration with the factory pattern

Use the factory pattern to integrate the database with other modules:

Example

File path: app.py

from

flask

import

Flask

def

create_app

(

)

:

    app

=

Flask

(

name

)

    app.

secret_key

=

"dev-secret-key"

   

Configure the database path (stored in the instance folder)

   

import

os

    app.

config

[

"DATABASE"

]

=

os

.

path

.

join

(

app.

instance_path

,

"runoob.db"

)

   

Ensure the instance folder exists

   

os

.

makedirs

(

app.

instance_path

,

exist_ok

=

True

)

   

Initialize the database

   

from

db

import

init_app

as

init_db

    init_db

(

app

)

   

Register the blueprint

   

from

auth

import

bp

as

auth_bp

   

from

blog

import

bp

as

blog_bp

    app.

register_blueprint

(

auth_bp

,

url_prefix

=

"/auth"

)

    app.

register_blueprint

(

blog_bp

)

   

return

app


Write a complete blog API

Combined with the database, implement article create, read, update, and delete (CRUD) operations:

Example

File path: blog.py

from

flask

import

Blueprint

,

request

,

jsonify

,

abort

,

g

from

db

import

get_db

bp

=

Blueprint

(

"blog"

,

name

)

@

bp.

get

(

"/api/posts"

)

def

list_posts

(

)

:

   

"""Get a list of all articles"""

    db

=

get_db

(

)

    posts

=

db.

execute

(

       

"SELECT p.id, p.title, p.body, p.created_at, u.username"

       

" FROM post p JOIN user u ON p.author_id = u.id"

       

" ORDER BY p.created_at DESC"

   

)

.

fetchall

(

)

   

Convert a list of Row objects to a list of dicts

   

return

jsonify

(

[

dict

(

post

)

for

post

in

posts

]

)

@

bp.

get

(

"/api/posts/int:post_id"

)

def

get_post

(

post_id

)

:

   

"""Get the details of a single article"""

    db

=

get_db

(

)

    post

=

db.

execute

(

       

"SELECT id, title, body, created_at FROM post WHERE id = ?"

,

       

(

post_id

,

)

   

)

.

fetchone

(

)

   

if

post

is

None

:

        abort

(

404

,

description

=

f

"Article {post_id} does not exist"

)

   

return

jsonify

(

dict

(

post

)

)

@

bp.

post

(

"/api/posts"

)

def

create_post

(

)

:

   

"""Create a new article"""

    data

=

request.

json

    title

=

data.

get

(

"title"

,

""

)

.

strip

(

)

    body

=

data.

get

(

"body"

,

""

)

.

strip

(

)

    author_id

=

data.

get

(

"author_id"

,

1

)

 

Default author ID

   

if

not

title:

       

return

jsonify

(

{

"error"

:

"Title cannot be empty"

}

)

,

400

    db

=

get_db

(

)

    cursor

=

db.

execute

(

       

"INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)"

,

       

(

title

,

body

,

author_id

)

   

)

    db.

commit

(

)

   

return

jsonify

(

{

"id"

: cursor.

lastrowid

,

"title"

: title

,

"message"

:

"Article created successfully"

}

)

,

201

@

bp.

put

(

"/api/posts/int:post_id"

)

def

update_post

(

post_id

)

:

   

"""Update an article"""

    data

=

request.

json

    title

=

data.

get

(

"title"

,

""

)

.

strip

(

)

    body

=

data.

get

(

"body"

,

""

)

.

strip

(

)

   

if

not

title:

       

return

jsonify

(

{

"error"

:

"Title cannot be empty"

}

)

,

400

    db

=

get_db

(

)

    db.

execute

(

       

"UPDATE post SET title = ?, body = ? WHERE id = ?"

,

       

(

title

,

body

,

post_id

)

   

)

    db.

commit

(

)

   

return

jsonify

(

{

"id"

: post_id

,

"message"

:

"Article updated successfully"

}

)

@

bp.

delete

(

"/api/posts/int:post_id"

)

def

delete_post

(

post_id

)

:

   

"""Delete an article"""

    db

=

get_db

(

)

    db.

execute

(

"DELETE FROM post WHERE id = ?"

,

(

post_id

,

)

)

    db.

commit

(

)

   

return

jsonify

(

{

"message"

:

"Article deleted"

}

)

Test the API:



# Get article list

$ curl http://127.0.0.1:5000/api/posts



# Create article

$ curl -X POST http://127.0.0.1:5000/api/posts \

  -H "Content-Type: application/json" \

  -d '{"title":"RUNOOB 教程","body":"Flask 入门教程内容","author_id":1}'



# Update article

$ curl -X PUT http://127.0.0.1:5000/api/posts/1 \

  -H "Content-Type: application/json" \

  -d '{"title":"RUNOOB 教程(修订版)","body":"更新后的内容"}'



# Delete article

$ curl -X DELETE http://127.0.0.1:5000/api/posts/1

Best Practices: When an API returns JSON data, use the correct HTTP status codes—for creation, use 201; for success, use 200; for client errors, use 400; for resource not found, use 404. This makes it easier for front-end code to determine the outcome of a request.


Database initialization command

You can create a custom command through the Flask CLI to initialize the database:



# Initialize database (create table structure)

(.venv) $ flask init-db



# Verify table created

(.venv) $ sqlite3 instance/runoob.db ".tables"

post  user


SQL injection protection

Using parameterized queries (? placeholders) is the key to preventing SQL injection:

Example

Correct approach: use ? placeholders (parameterized queries)

The SQLite driver automatically escapes parameters, preventing malicious input from being executed as SQL

db.

execute

(

"SELECT * FROM user WHERE username = ?"

,

(

username

,

)

)

Wrong approach: concatenating SQL with an f-string (extremely dangerous!)

db.execute(f"SELECT * FROM user WHERE username = '{username}'")

Malicious input '; DROP TABLE user; -- would delete the entire table!


Using Flask-SQLAlchemy (advanced, optional reading)

For large projects, writing SQL manually gradually becomes tedious.

Flask-SQLAlchemy is a popular extension that provides ORM (object-relational mapping) capabilities:

Example

Installation: pip install flask-sqlalchemy

from

flask

import

Flask

from

flask_sqlalchemy

import

SQLAlchemy

app

=

Flask

(

name

)

app.

config

[

"SQLALCHEMY_DATABASE_URI"

]

=

"sqlite:///runoob.db"

db

=

SQLAlchemy

(

app

)

Define data models (table structures represented by Python classes)

class

User

(

db.

Model

)

:

   

id

=

db.

Column

(

db.

Integer

,

primary_key

=

True

)

    username

=

db.

Column

(

db.

String

(

80

)

,

unique

=

True

,

nullable

=

False

)

   

email

=

db.

Column

(

db.

String

(

120

)

,

unique

=

True

,

nullable

=

False

)

   

def

repr

(

self

)

:

       

return

f

""

Create a table

with

app.

app_context

(

)

:

    db.

create_all

(

)

Create users

user

=

User

(

username

=

"runoob"

,

email

=

"test@runoob.com"

)

db.

session

.

add

(

user

)

db.

session

.

commit

(

)

Query users

users

=

User.

query

.

all

(

)

runoob_user

=

User.

query

.

filter_by

(

username

=

"runoob"

)

.

first

(

)

This chapter uses native SQLite to avoid introducing extra dependencies, making it suitable for learning and small projects. For real production projects, SQLAlchemy or a similar ORM is recommended, as it can significantly reduce repetitive code and improve security.