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 AiosqliteConfig, AiosqliteDriver
11from sqlspec.core import SQL
12from sqlspec.extensions.litestar import SQLSpecPlugin
13
14registry = aiosqlite_registry()
15config = registry.get_config(AiosqliteConfig)
16plugin = SQLSpecPlugin(sqlspec=registry)
17
18
19async def seed_database() -> None:
20 """Ensure the demo schema exists and seed a few rows."""
21 async with config.provide_session() as session:
22 await session.execute(CREATE_ARTICLES)
23 for row in ARTICLES:
24 await session.execute(
25 SQL(
26 """
27 INSERT OR REPLACE INTO articles (id, title, body)
28 VALUES (:id, :title, :body)
29 """
30 ),
31 row,
32 )
33
34
35@get("/articles")
36async def list_articles(db_session: "AiosqliteDriver") -> "list[dict[str, Any]]":
37 """Return all demo articles."""
38 result = await db_session.execute(SQL("SELECT id, title, body FROM articles ORDER BY id"))
39 return result.all()
40
41
42app = Litestar(route_handlers=[list_articles], on_startup=[seed_database], plugins=[plugin], debug=True)
43
44
45def main() -> None:
46 """Seed the database once when run as a script."""
47 asyncio.run(seed_database())
48
49
50if __name__ == "__main__":
51 main()