Litestar + AioSQLite Application¶
Seed a lightweight article table with SQLSpec and expose it through Litestar using the async aiosqlite adapter.
Run locally:
uv run python docs/examples/frameworks/litestar/aiosqlite_app.py
Source¶
1"""Litestar application backed by SQLSpec and AioSQLite."""
2
3import asyncio
4from typing import Any
5
6from litestar import Litestar, get
7
8from docs.examples.shared.configs import aiosqlite_registry
9from docs.examples.shared.data import ARTICLES, CREATE_ARTICLES
10from sqlspec.adapters.aiosqlite import AiosqliteDriver
11from sqlspec.core import SQL
12from sqlspec.extensions.litestar import SQLSpecPlugin
13
14registry, config = aiosqlite_registry()
15plugin = SQLSpecPlugin(sqlspec=registry)
16
17
18async def seed_database() -> None:
19 """Ensure the demo schema exists and seed a few rows."""
20 async with config.provide_session() as session:
21 await session.execute(CREATE_ARTICLES)
22 for row in ARTICLES:
23 await session.execute(
24 SQL(
25 """
26 INSERT OR REPLACE INTO articles (id, title, body)
27 VALUES (:id, :title, :body)
28 """
29 ),
30 row,
31 )
32
33
34@get("/articles")
35async def list_articles(db_session: "AiosqliteDriver") -> "list[dict[str, Any]]":
36 """Return all demo articles."""
37 result = await db_session.execute(SQL("SELECT id, title, body FROM articles ORDER BY id"))
38 return result.all()
39
40
41app = Litestar(route_handlers=[list_articles], on_startup=[seed_database], plugins=[plugin], debug=True)
42
43
44def main() -> None:
45 """Seed the database once when run as a script."""
46 asyncio.run(seed_database())
47
48
49if __name__ == "__main__":
50 main()