Factory functions for SQLAlchemy async engine and session management
Project description
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 URLecho(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 instanceexpire_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.0asyncpg>=0.29.0(PostgreSQL driver)aiosqlite>=0.19.0(SQLite driver, optional)
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sqlalchemy_async_session_factory-0.1.0.tar.gz.
File metadata
- Download URL: sqlalchemy_async_session_factory-0.1.0.tar.gz
- Upload date:
- Size: 5.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
015feecc2a648ea101026aeba924d5db5e1e718676437d3b544ef29cb0b24510
|
|
| MD5 |
772064e3602e0c17e31139a56364617f
|
|
| BLAKE2b-256 |
3c684122c5bf87f581b2eb8525e2ae1fbad91ef591f3cf4bb5a6b402d58b77ee
|
File details
Details for the file sqlalchemy_async_session_factory-0.1.0-py3-none-any.whl.
File metadata
- Download URL: sqlalchemy_async_session_factory-0.1.0-py3-none-any.whl
- Upload date:
- Size: 6.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8ae72dd5918cfa68d0ab1d58bbcd639ca71fa43af776cbbb40ed93e8ffc7447d
|
|
| MD5 |
4e9100889dc9a9ff956e31ad969140fe
|
|
| BLAKE2b-256 |
d7426ab3098c5ac6cb5a713b1786bb5025c625ebac572fbdf51a38baba35bb6e
|