Litestar + SQLite Application¶
Serve SQLSpec-backed content through Litestar using the synchronous SQLite adapter.
uv run python docs/examples/frameworks/litestar/sqlite_app.py
Source¶
1"""Litestar example backed by SQLSpec and SQLite."""
2
3from typing import Any
4
5from litestar import Litestar, get
6
7from docs.examples.shared.configs import sqlite_registry
8from docs.examples.shared.data import ARTICLES, CREATE_ARTICLES
9from sqlspec.adapters.sqlite import SqliteConfig, SqliteDriver
10from sqlspec.core import SQL
11from sqlspec.extensions.litestar import SQLSpecPlugin
12
13registry = sqlite_registry()
14config = registry.get_config(SqliteConfig)
15plugin = SQLSpecPlugin(sqlspec=registry)
16
17
18def seed_database() -> None:
19 """Create the articles table and seed 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: "SqliteDriver") -> "list[dict[str, Any]]":
36 """Return all articles from SQLite."""
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 SQLite once when invoked as a script."""
46 seed_database()
47
48
49if __name__ == "__main__":
50 main()