Starlette#
Starlette extension providing middleware-based session management, automatic transaction handling, and connection pooling lifecycle management.
Configuration#
Use sqlspec.config.StarletteConfig in extension_config["starlette"].
These settings apply across adapters; no adapter-specific subtype is needed.
- class sqlspec.config.StarletteConfig[source]
Bases:
TypedDictConfiguration options for Starlette SQLSpec extension.
All fields are optional with sensible defaults. Use in extension_config["starlette"]:
- connection_key: NotRequired[str]
'db_connection'
- Type:
Key for storing connection in request.state. Default
- pool_key: NotRequired[str]
'db_pool'
- Type:
Key for storing connection pool in app.state. Default
- session_key: NotRequired[str]
'db_session'
- Type:
Key for storing session in request.state. Default
- commit_mode: NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]
'manual'
manual: No automatic commit/rollback
autocommit: Commit on 2xx, rollback otherwise
autocommit_include_redirect: Commit on 2xx-3xx, rollback otherwise
- Type:
Transaction commit mode. Default
- extra_commit_statuses: NotRequired[set[int]]
- Type:
Additional HTTP status codes that trigger commit. Default
- extra_rollback_statuses: NotRequired[set[int]]
- Type:
Additional HTTP status codes that trigger rollback. Default
- disable_di: NotRequired[bool]
False. When True, the Starlette/FastAPI extension will not add middleware for managing database connections and sessions. Users are responsible for managing the database lifecycle manually via their own DI solution.
- Type:
Disable built-in dependency injection. Default
- enable_sqlcommenter_middleware: NotRequired[bool]
True. When the driver's
StatementConfighasenable_sqlcommenter=True, the middleware is registered automatically. Set toFalseto explicitly disable middleware registration.- Type:
Control automatic SQLCommenter middleware registration. Default
- sqlcommenter_framework: NotRequired[str]
'starlette'. Set to 'fastapi' when using FastAPI.
- Type:
Framework name for SQLCommenter attributes. Default
Plugin#
- class sqlspec.extensions.starlette.SQLSpecPlugin[source]#
Bases:
objectSQLSpec integration for Starlette applications.
Provides middleware-based session management, automatic transaction handling, and connection pooling lifecycle management.
- init_app(app)[source]#
Initialize Starlette application with SQLSpec.
Validates configuration, wraps lifespan, and adds middleware.
- lifespan(app)[source]#
Manage connection pool lifecycle.
- Parameters:
app¶ (
Starlette) -- Starlette application instance.- Yields:
None
Middleware#
- class sqlspec.extensions.starlette.SQLSpecAutocommitMiddleware[source]#
Bases:
BaseHTTPMiddlewareMiddleware for autocommit transaction mode.
Acquires connection, commits on success status codes, rollbacks on error status codes.
- __init__(app, config_state)[source]#
Initialize middleware.
- Parameters:
config_state¶ (
SQLSpecConfigState) -- Configuration state for this database.
- class sqlspec.extensions.starlette.SQLSpecManualMiddleware[source]#
Bases:
BaseHTTPMiddlewareMiddleware for manual transaction mode.
Acquires connection from pool, stores in request.state, releases after request. No automatic commit or rollback - user code must handle transactions.
- __init__(app, config_state)[source]#
Initialize middleware.
- Parameters:
config_state¶ (
SQLSpecConfigState) -- Configuration state for this database.
- class sqlspec.extensions.starlette.middleware.CorrelationMiddleware[source]#
Bases:
BaseHTTPMiddlewareMiddleware for correlation ID extraction and propagation.
Extracts correlation IDs from request headers (or generates new ones) and propagates them through the request lifecycle via CorrelationContext.
- The middleware:
Extracts correlation ID from configurable headers
Sets it in the CorrelationContext for async/sync access
Stores it in request.state.correlation_id
Adds X-Correlation-ID header to the response
Cleans up the context on request completion
- __init__(app, *, primary_header='x-request-id', additional_headers=None, auto_trace_headers=True, max_length=128)[source]#
Initialize correlation middleware.
- Parameters:
primary_header¶ (
str) -- The primary header to check first. Defaults to "x-request-id".additional_headers¶ (
tuple[str,...] |None) -- Additional headers to check after the primary header.auto_trace_headers¶ (
bool) -- If True, include standard trace context headers as fallbacks.max_length¶ (
int) -- Maximum length for correlation IDs. Defaults to 128.
- class sqlspec.extensions.starlette.middleware.SQLCommenterMiddleware[source]#
Bases:
BaseHTTPMiddlewareMiddleware that populates SQLCommenterContext with request attributes.
Extracts route and endpoint information from the Starlette/FastAPI request and sets them in
SQLCommenterContextfor the duration of the request.
State#
- class sqlspec.extensions.starlette.SQLSpecConfigState[source]#
Bases:
objectInternal state for each database configuration.
Tracks all configuration parameters needed for middleware and session management.
- should_commit(status_code)[source]#
Return whether a response status should trigger a commit.
- Return type:
- should_rollback(status_code)[source]#
Return whether a response status should trigger a rollback.
- Return type:
- __init__(config, connection_key, pool_key, session_key, commit_mode, extra_commit_statuses, extra_rollback_statuses, disable_di, enable_correlation_middleware=False, correlation_header='x-request-id', correlation_headers=None, auto_trace_headers=True, enable_sqlcommenter_middleware=True, sqlcommenter_framework='starlette')#
Helpers#
- sqlspec.extensions.starlette.get_connection_from_request(request, config_state)[source]#
Get database connection from request state.
- Parameters:
config_state¶ (
SQLSpecConfigState) -- Configuration state for the database.
- Return type:
- Returns:
Database connection object.
- sqlspec.extensions.starlette.get_or_create_session(request, config_state)[source]#
Get or create database session for request.
Sessions are cached per request to ensure the same session instance is returned for multiple calls within the same request.
- Parameters:
config_state¶ (
SQLSpecConfigState) -- Configuration state for the database.
- Return type:
- Returns:
Database session (driver instance).