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 DuckDBConfig, DuckDBDriver
10from sqlspec.core import SQL
11from sqlspec.extensions.litestar import SQLSpecPlugin
12
13registry = duckdb_registry()
14config = registry.get_config(DuckDBConfig)
15plugin = SQLSpecPlugin(sqlspec=registry)
16
17
18def seed_database() -> None:
19 """Create the articles table and insert demo rows."""
20 with config.provide_session() as session:
21 session.execute(CREATE_ARTICLES)
22 for row in ARTICLES:
23 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", sync_to_thread=False)
35def list_articles(db_session: "DuckDBDriver") -> "list[dict[str, Any]]":
36 """Return the DuckDB article dataset."""
37 result = 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 DuckDB once when invoked as a script."""
46 seed_database()
47
48
49if __name__ == "__main__":
50 main()