0
# Flask-SQLAlchemy
1
2
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy with Flask by providing useful defaults and extra helpers that make it easier to accomplish common database tasks.
3
4
## Package Information
5
6
- **Package Name**: Flask-SQLAlchemy
7
- **Language**: Python
8
- **Installation**: `pip install Flask-SQLAlchemy`
9
10
## Core Imports
11
12
```python
13
from flask_sqlalchemy import SQLAlchemy
14
```
15
16
Import specific components from submodules (optional):
17
18
```python
19
from flask_sqlalchemy.pagination import Pagination
20
from flask_sqlalchemy.query import Query
21
from flask_sqlalchemy.record_queries import get_recorded_queries
22
```
23
24
## Basic Usage
25
26
```python
27
from flask import Flask
28
from flask_sqlalchemy import SQLAlchemy
29
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
30
31
app = Flask(__name__)
32
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///example.sqlite"
33
34
class Base(DeclarativeBase):
35
pass
36
37
db = SQLAlchemy(app, model_class=Base)
38
39
class User(db.Model):
40
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
41
username: Mapped[str] = mapped_column(db.String, unique=True, nullable=False)
42
43
with app.app_context():
44
db.create_all()
45
46
# Add and commit data
47
db.session.add(User(username="example"))
48
db.session.commit()
49
50
# Query data
51
users = db.session.execute(db.select(User)).scalars()
52
```
53
54
## Architecture
55
56
Flask-SQLAlchemy follows a Flask extension pattern with several key components:
57
58
- **SQLAlchemy Extension**: Main class that integrates SQLAlchemy with Flask applications
59
- **Model Base Classes**: Declarative base classes with Flask-specific features like automatic table naming
60
- **Session Management**: Flask application context-aware sessions with automatic cleanup
61
- **Query Interface**: Enhanced query classes with Flask conveniences like `get_or_404()`
62
- **Pagination**: Built-in pagination support for large result sets
63
- **Multiple Database Support**: Bind key system for multiple databases
64
65
The extension provides seamless integration between Flask's application context system and SQLAlchemy's session management, ensuring proper database connection handling across request lifecycles.
66
67
## Capabilities
68
69
### Extension Setup and Configuration
70
71
Core extension class initialization, Flask app integration, and database configuration management. This includes setting up database URIs, engine options, and binding multiple databases.
72
73
```python { .api }
74
class SQLAlchemy:
75
Query: type[Query] # The default query class used by Model.query
76
77
def __init__(
78
self,
79
app: Flask | None = None,
80
*,
81
metadata: sa.MetaData | None = None,
82
session_options: dict[str, Any] | None = None,
83
query_class: type[Query] = Query,
84
model_class: Any = Model,
85
engine_options: dict[str, Any] | None = None,
86
add_models_to_shell: bool = True,
87
disable_autonaming: bool = False,
88
): ...
89
90
def init_app(self, app: Flask) -> None: ...
91
```
92
93
[Extension Setup](./extension-setup.md)
94
95
### Database Models and Tables
96
97
Declarative model base classes with automatic table naming, bind key support, and Flask integration features. Includes table creation utilities and metadata management.
98
99
```python { .api }
100
class Model:
101
query_class: type[Query]
102
query: Query
103
104
def should_set_tablename(cls: type) -> bool: ...
105
def camel_to_snake_case(name: str) -> str: ...
106
```
107
108
[Models and Tables](./models-tables.md)
109
110
### Session and Database Operations
111
112
Session management with Flask application context integration, bind key resolution, and automatic session cleanup. Core database operations and transaction handling.
113
114
```python { .api }
115
class Session(sa_orm.Session):
116
def get_bind(
117
self,
118
mapper: Any | None = None,
119
clause: Any | None = None,
120
bind: sa.engine.Engine | sa.engine.Connection | None = None,
121
**kwargs: Any,
122
) -> sa.engine.Engine | sa.engine.Connection: ...
123
```
124
125
[Session Management](./session-management.md)
126
127
### Query Interface and Conveniences
128
129
Enhanced query classes with Flask-specific convenience methods for common web patterns like 404 error handling and result processing.
130
131
```python { .api }
132
class Query(sa_orm.Query):
133
def get_or_404(self, ident: Any, description: str | None = None) -> Any: ...
134
def first_or_404(self, description: str | None = None) -> Any: ...
135
def one_or_404(self, description: str | None = None) -> Any: ...
136
def paginate(*, page: int | None = None, per_page: int | None = None, **kwargs) -> Pagination: ...
137
```
138
139
[Query Interface](./query-interface.md)
140
141
### Pagination
142
143
Built-in pagination support for both modern SQLAlchemy select statements and legacy Query objects, with request parameter integration and pagination widget helpers.
144
145
```python { .api }
146
class Pagination:
147
page: int
148
per_page: int
149
total: int | None
150
items: list[Any]
151
152
def prev(*, error_out: bool = False) -> Pagination: ...
153
def next(*, error_out: bool = False) -> Pagination: ...
154
def iter_pages(**kwargs) -> Iterator[int | None]: ...
155
```
156
157
[Pagination](./pagination.md)
158
159
### Development and Debugging
160
161
Optional features for development including query recording, modification tracking, and Flask shell integration for enhanced debugging capabilities.
162
163
```python { .api }
164
def get_recorded_queries() -> list[_QueryInfo]: ...
165
166
models_committed: Signal
167
before_models_committed: Signal
168
```
169
170
[Development Tools](./development-tools.md)
171
172
## Configuration
173
174
Flask-SQLAlchemy uses the following configuration variables:
175
176
- **SQLALCHEMY_DATABASE_URI**: Default database connection URI
177
- **SQLALCHEMY_ENGINE_OPTIONS**: Default engine configuration options
178
- **SQLALCHEMY_ECHO**: Enable SQLAlchemy query logging
179
- **SQLALCHEMY_BINDS**: Mapping of bind keys to database URIs/options
180
- **SQLALCHEMY_RECORD_QUERIES**: Enable query recording functionality
181
- **SQLALCHEMY_TRACK_MODIFICATIONS**: Enable model modification tracking
182
183
## Types
184
185
```python { .api }
186
from typing import Any, Mapping, TypeVar, Union, Type
187
import sqlalchemy as sa
188
import sqlalchemy.orm as sa_orm
189
190
# Type variables for model class customization
191
_FSA_MCT = TypeVar(
192
"_FSA_MCT",
193
bound=Union[
194
Type[Model],
195
sa_orm.DeclarativeMeta,
196
Type[sa_orm.DeclarativeBase],
197
Type[sa_orm.DeclarativeBaseNoMeta],
198
]
199
)
200
"""
201
Type variable for Flask-SQLAlchemy model class parameter.
202
203
Used in SQLAlchemy.__init__() to accept various model class types:
204
- Type[Model]: Flask-SQLAlchemy's default Model class
205
- sa_orm.DeclarativeMeta: SQLAlchemy 1.x declarative metaclass
206
- Type[sa_orm.DeclarativeBase]: SQLAlchemy 2.x declarative base
207
- Type[sa_orm.DeclarativeBaseNoMeta]: SQLAlchemy 2.x base without metaclass
208
209
This allows flexible model class customization while maintaining type safety.
210
"""
211
212
_O = TypeVar("_O", bound=object)
213
"""
214
Generic type variable for object returns.
215
216
Used in methods like get_or_404() to preserve the return type of the
217
queried entity while ensuring type safety.
218
"""
219
```