Created
February 15, 2026 04:20
-
-
Save tooruu/764155357d7c98137123863a3501b3a3 to your computer and use it in GitHub Desktop.
Async SQLModel SQLite primer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from sqlalchemy import event | |
| from sqlalchemy.ext.asyncio import create_async_engine | |
| from sqlalchemy.orm import sessionmaker | |
| from sqlmodel import Field, SQLModel | |
| from sqlmodel.ext.asyncio.session import AsyncSession | |
| class User(SQLModel, table=True): | |
| id: int | None = Field(default=None, primary_key=True) | |
| name: str | |
| engine = create_async_engine("sqlite+aiosqlite:///database.sqlite") | |
| SessionLocal = sessionmaker(engine, class_=AsyncSession, autoflush=False, expire_on_commit=False) | |
| @event.listens_for(engine.sync_engine, "connect") | |
| def set_sqlite_pragma(dbapi_connection, connection_record): | |
| cursor = dbapi_connection.cursor() | |
| cursor.execute("PRAGMA journal_mode=WAL") | |
| cursor.execute("PRAGMA synchronous=NORMAL") | |
| cursor.execute("PRAGMA foreign_keys=ON") | |
| cursor.close() | |
| async def main(): | |
| async with engine.begin() as conn: | |
| await conn.run_sync(SQLModel.metadata.create_all) | |
| async with SessionLocal.begin() as session: | |
| session.add(User(name="John")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment