|
| 1 | +# Async Tools |
| 2 | + |
| 3 | +SQLModel supports asynchronous execution via SQLAlchemy's `ext.asyncio`. This is very useful when working with high-concurrency applications, such as FastAPI. |
| 4 | + |
| 5 | +## `AsyncSession` and `create_async_engine` |
| 6 | + |
| 7 | +Instead of `create_engine`, you use `create_async_engine`. And instead of `Session`, you use `AsyncSession`. |
| 8 | + |
| 9 | +```python |
| 10 | +from sqlmodel import SQLModel, Field, select |
| 11 | +from sqlmodel.ext.asyncio.session import AsyncSession |
| 12 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 13 | + |
| 14 | +class Hero(SQLModel, table=True): |
| 15 | + id: int | None = Field(default=None, primary_key=True) |
| 16 | + name: str = Field(index=True) |
| 17 | + secret_name: str |
| 18 | + age: int | None = Field(default=None, index=True) |
| 19 | + |
| 20 | +# Note the +asyncpg in the database URL |
| 21 | +sqlite_url = "postgresql+asyncpg://user:password@localhost/db" |
| 22 | +engine = create_async_engine(sqlite_url, echo=True) |
| 23 | + |
| 24 | +async def create_db_and_tables(): |
| 25 | + async with engine.begin() as conn: |
| 26 | + await conn.run_sync(SQLModel.metadata.create_all) |
| 27 | + |
| 28 | +async def create_heroes(): |
| 29 | + hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") |
| 30 | + async with AsyncSession(engine) as session: |
| 31 | + session.add(hero_1) |
| 32 | + await session.commit() |
| 33 | + await session.refresh(hero_1) |
| 34 | + print("Created hero:", hero_1) |
| 35 | + |
| 36 | +async def read_heroes(): |
| 37 | + async with AsyncSession(engine) as session: |
| 38 | + statement = select(Hero).where(Hero.name == "Deadpond") |
| 39 | + results = await session.exec(statement) |
| 40 | + hero = results.first() |
| 41 | + print("Hero:", hero) |
| 42 | +``` |
| 43 | + |
| 44 | +## Using with FastAPI |
| 45 | + |
| 46 | +When integrating with FastAPI, you can use `AsyncSession` as a dependency. |
| 47 | + |
| 48 | +```python |
| 49 | +from fastapi import FastAPI, Depends |
| 50 | +from sqlmodel.ext.asyncio.session import AsyncSession |
| 51 | + |
| 52 | +app = FastAPI() |
| 53 | + |
| 54 | +async def get_session(): |
| 55 | + async with AsyncSession(engine) as session: |
| 56 | + yield session |
| 57 | + |
| 58 | +@app.get("/heroes/") |
| 59 | +async def read_heroes(session: AsyncSession = Depends(get_session)): |
| 60 | + statement = select(Hero) |
| 61 | + result = await session.exec(statement) |
| 62 | + heroes = result.all() |
| 63 | + return heroes |
| 64 | +``` |
0 commit comments