-
Notifications
You must be signed in to change notification settings - Fork 0
Database Asynchronous Access
James Brucker edited this page Jun 21, 2025
·
3 revisions
To improve throughput of a database-backed web service, we can use asynchronous database operations. PostgreSQL and Sqlite support asynchronous operations, but the support is less mature than the default synchronous operation.
- Install package:
asyncpg - Database URL:
postgresql+asyncpg://{db_username}:{db_secret}@{db_hostname}:{port}/{database_name}
- Install package: `
- Database URL:
sqlite+aiosqlite:///{database_name}May also include a host and path.
Install package: sqlalchemy[asyncio]
Main classes for asynchronous I/O.
-
AsyncEngine an async version of the standard
EngineAPI. -
AsyncConnection an async Connection manager. Create using
asyncEngine.connect()orasyncEngine.begin(). -
AsyncSession represents a single, stateful database transaction. Concurrent tasks should each use a separate
AsyncSessionobject.
Example from SqlAlchemy documentation:
Create database engine and async connection, using canonical SqlAlchemy 2.0 package names:
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import declarative_base
engine - create_async_engine(
database_url,
future=True, # Use SqlAlchemy 2.0 style API
echo=True # Optional, display SQL on console or log for testing
)