Flask#
SQLSpec provides a Flask extension that manages database connections within the Flask request lifecycle. The extension registers connection pool setup and teardown with Flask's application context hooks.
Installation#
Install SQLSpec with the Flask extra:
uv add "sqlspec[flask]"
pip install "sqlspec[flask]"
poetry add "sqlspec[flask]"
pdm add "sqlspec[flask]"
Basic Setup#
Create a SQLSpec instance, register your database config, and attach the plugin to your
Flask app. Use plugin.get_session() inside request handlers to obtain a session.
flask basic setup#from flask import Flask
from sqlspec import SQLSpec
from sqlspec.adapters.sqlite import SqliteConfig, SqliteDriver
from sqlspec.extensions.flask import SQLSpecPlugin
# Create SQLSpec and plugin at module level
sqlspec = SQLSpec()
sqlspec.add_config(SqliteConfig(connection_config={"database": ":memory:"}))
plugin = SQLSpecPlugin(sqlspec)
def create_app() -> Flask:
"""Application factory pattern."""
app = Flask(__name__)
plugin.init_app(app)
@app.get("/health")
def health() -> dict[str, int]:
db: SqliteDriver = plugin.get_session()
result = db.execute("select 1 as ok")
return result.one()
return app
app = create_app()
Key Concepts#
- Request-Scoped Sessions
Sessions obtained via
get_session()are bound to the current request context. They are automatically closed when the request finishes.- Application Factory Pattern
When using the factory pattern, initialize the plugin in your
create_appfunction:def create_app(): app = Flask(__name__) sqlspec = SQLSpec() sqlspec.add_config(SqliteConfig(...)) plugin = SQLSpecPlugin(sqlspec, app) return app
- Sync Execution
Flask operates synchronously by default. Use sync adapters like
SqliteConfigorPsycopgSyncConfigfor straightforward integration.