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:

pip install "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
from sqlspec.extensions.flask import SQLSpecPlugin

sqlspec = SQLSpec()
sqlspec.add_config(SqliteConfig(connection_config={"database": ":memory:"}))

app = Flask(__name__)
plugin = SQLSpecPlugin(sqlspec, app)

@app.get("/health")
def health() -> Any:
    session = plugin.get_session()
    result = session.execute("select 1 as ok")
    return result.one()

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_app function:

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 SqliteConfig or PsycopgSyncConfig for straightforward integration.