Litestar + DuckDB Application¶
Serve DuckDB-backed content through Litestar without external services.
Run locally:
uv run python docs/examples/frameworks/litestar/duckdb_app.py
Source¶
1"""Litestar example that serves DuckDB data through SQLSpec."""
2
3from typing import Any
4
5from litestar import Litestar, get
6
7from docs.examples.shared.configs import duckdb_registry
8from docs.examples.shared.data import ARTICLES, CREATE_ARTICLES
9from sqlspec.adapters.duckdb import DuckDBDriver
10from sqlspec.core import SQL
11from sqlspec.extensions.litestar import SQLSpecPlugin
12
13registry, config = duckdb_registry()
14plugin = SQLSpecPlugin(sqlspec=registry)
15
16
17def seed_database() -> None:
18 """Create the articles table and insert demo rows."""
19 with config.provide_session() as session:
20 session.execute(CREATE_ARTICLES)
21 for row in ARTICLES:
22 session.execute(
23 SQL(
24 """
25 INSERT OR REPLACE INTO articles (id, title, body)
26 VALUES (:id, :title, :body)
27 """
28 ),
29 row,
30 )
31
32
33@get("/articles", sync_to_thread=False)
34def list_articles(db_session: "DuckDBDriver") -> "list[dict[str, Any]]":
35 """Return the DuckDB article dataset."""
36 result = db_session.execute(SQL("SELECT id, title, body FROM articles ORDER BY id"))
37 return result.all()
38
39
40app = Litestar(route_handlers=[list_articles], on_startup=[seed_database], plugins=[plugin], debug=True)
41
42
43def main() -> None:
44 """Seed DuckDB once when invoked as a script."""
45 seed_database()
46
47
48if __name__ == "__main__":
49 main()