Flask-SQLAlchemy Setup & Engine Configuration
Flask-SQLAlchemy Setup & Engine Configuration
Persistent data storage is the backbone of web applications. While Python supports raw database drivers (like sqlite3 or psycopg2), writing raw SQL strings is tedious, error-prone, and vulnerable to SQL injection.
Flask-SQLAlchemy integrates SQLAlchemy—the premier Object Relational Mapper (ORM) for Python—with Flask. It manages database engines, handles connection pooling, and simplifies session lifecycles.
1. Installing Flask-SQLAlchemy 3.x
Install the extension:
For PostgreSQL or MySQL support, install the corresponding database driver:
2. Configuring the Database URI
Flask-SQLAlchemy connects to your database via SQLALCHEMY_DATABASE_URI. The URI format follows standard RFC connection strings:
Common Database URI Formats:
| Database Engine | SQLALCHEMY_DATABASE_URI Example |
|---|---|
| SQLite (Local File) | sqlite:///app.db (relative to instance folder) |
| SQLite (In-Memory for Tests) | sqlite:///:memory: |
| PostgreSQL | postgresql+psycopg2://db_user:secret_pass@localhost:5432/msk_db |
| MySQL / MariaDB | mysql+pymysql://db_user:secret_pass@localhost:3306/msk_db |
3. Initializing the SQLAlchemy Extension
In modern Flask-SQLAlchemy 3.x, initialize the SQLAlchemy object and bind it to your application:
4. Understanding Application Context and db.create_all()
In Flask-SQLAlchemy 3.x, database operations (like creating tables) must run within Flask's application context:
Attempting to run db.create_all() outside with app.app_context(): will raise an ActiveContextError or RuntimeError: Working outside of application context.
Practice Quiz
SQLALCHEMY_TRACK_MODIFICATIONS be explicitly set to False?db.create_all() be executed inside with app.app_context(): in Flask-SQLAlchemy 3.x?sqlite:///app.db (with three slashes) denote?pool_recycle in SQLALCHEMY_ENGINE_OPTIONS?Defining Models & Column Constraints
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Flash Messaging System & User Feedback UI | Defining Models & Column Constraints |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.