Skip to main content

SQLAlchemy Async Session Factory

Factory functions for SQLAlchemy async engine and session management with FastAPI integration.

Extracted from: GridFlow backend/src/database.py

Installation

# PostgreSQL support (recommended)
pip install sqlalchemy-async-session-factory

# SQLite support
pip install sqlalchemy-async-session-factory[sqlite]

Features

  • Engine Factory: Create async engine with connection pooling
  • Session Factory: Create async session maker
  • FastAPI Dependency: Generate session dependency for FastAPI
  • Pool Management: Connection pool event handlers and warning suppression

Usage

Basic Setup

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_async_session_factory import (
    create_async_engine_with_pool,
    create_async_session_maker,
    create_session_dependency,
    suppress_pool_warnings
)

# Suppress pool warnings (call once at startup)
suppress_pool_warnings()

# Create engine
engine = create_async_engine_with_pool(
    "postgresql+asyncpg://user:pass@localhost/db",
    pool_size=10,
    echo=True
)

# Create session maker
SessionLocal = create_async_session_maker(engine)

# Create FastAPI dependency
get_db = create_session_dependency(SessionLocal)

With FastAPI

from fastapi import FastAPI, Depends
from sqlalchemy.ext.asyncio import AsyncSession

app = FastAPI()

@app.get("/items")
async def read_items(db: AsyncSession = Depends(get_db)):
    # Use db session
    result = await db.execute("SELECT * FROM items")
    return result.scalars().all()

Connection Pool Event Handlers

from sqlalchemy_async_session_factory import setup_pool_event_handlers

# Setup event handlers for graceful cleanup
setup_pool_event_handlers(engine)

Manual Session Usage

# Use session directly
async with SessionLocal() as session:
    result = await session.execute("SELECT * FROM items")
    items = result.scalars().all()

API Reference

create_async_engine_with_pool(...)

Create async engine with connection pooling.

Parameters:

  • database_url (str): Database connection URL
  • echo (bool): Echo SQL queries (default: False)
  • pool_size (int): Number of connections (default: 5)
  • max_overflow (int): Max overflow connections (default: 5)
  • pool_timeout (int): Connection timeout seconds (default: 30)
  • pool_pre_ping (bool): Test connections (default: True)
  • pool_recycle (int): Recycle after seconds (default: 300)

Returns:

  • AsyncEngine: Configured engine

create_async_session_maker(...)

Create async session maker.

Parameters:

  • engine (AsyncEngine): Engine instance
  • expire_on_commit (bool): Expire objects (default: False)

Returns:

  • async_sessionmaker[AsyncSession]: Session maker

create_session_dependency(...)

Create FastAPI session dependency.

Parameters:

  • session_maker (async_sessionmaker): Session maker

Returns:

  • Callable: Dependency function

suppress_pool_warnings()

Suppress connection pool warnings during cleanup.

setup_pool_event_handlers(engine)

Setup event handlers for connection pool.

Parameters:

  • engine (AsyncEngine): Engine instance

Supported Databases

PostgreSQL (Recommended)

engine = create_async_engine_with_pool(
    "postgresql+asyncpg://user:pass@localhost:5432/db"
)

SQLite

engine = create_async_engine_with_pool(
    "sqlite+aiosqlite:///./app.db"
)

Dependencies

  • sqlalchemy[asyncio]>=2.0.0
  • asyncpg>=0.29.0 (PostgreSQL driver)
  • aiosqlite>=0.19.0 (SQLite driver, optional)

License

MIT

Metadata

Release files for sqlalchemy-async-session-factory 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sqlalchemy-async-session-factory 0.1.0
File Size Uploaded Provenance Actions
sqlalchemy_async_session_factory-0.1.0.tar.gz 5.4 kB Without provenance Details for sqlalchemy_async_session_factory-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sqlalchemy-async-session-factory 0.1.0
File Interpreter ABI Platform Actions
sqlalchemy_async_session_factory-0.1.0-py3-none-any.whl Python 3 none any Details for sqlalchemy_async_session_factory-0.1.0-py3-none-any.whl

Total release size: 11.4 kB

Release files / sqlalchemy_async_session_factory-0.1.0.tar.gz

Download URL sqlalchemy_async_session_factory-0.1.0.tar.gz
Size 5.4 kB
Tags Source
SHA-256 checksum
How to use checksums
015feecc2a648ea101026aeba924d5db5e1e718676437d3b544ef29cb0b24510
BLAKE2b-256 checksum
How to use checksums
3c684122c5bf87f581b2eb8525e2ae1fbad91ef591f3cf4bb5a6b402d58b77ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

Release files / sqlalchemy_async_session_factory-0.1.0-py3-none-any.whl

Download URL sqlalchemy_async_session_factory-0.1.0-py3-none-any.whl
Size 6.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8ae72dd5918cfa68d0ab1d58bbcd639ca71fa43af776cbbb40ed93e8ffc7447d
BLAKE2b-256 checksum
How to use checksums
d7426ab3098c5ac6cb5a713b1786bb5025c625ebac572fbdf51a38baba35bb6e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

Security for sqlalchemy-async-session-factory 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page