Flask + SQLite Application

Serve SQLSpec data through Flask backed by the synchronous SQLite adapter.

uv run python docs/examples/frameworks/flask/sqlite_app.py

Source

 1"""Flask routes using SQLSpec's synchronous SQLite adapter."""
 2
 3from flask import Flask, Response, jsonify
 4
 5from docs.examples.shared.configs import sqlite_registry
 6from docs.examples.shared.data import ARTICLES, CREATE_ARTICLES
 7from sqlspec.core import SQL
 8
 9__all__ = ("list_articles", "main", "seed_database")
10
11
12registry, config = sqlite_registry()
13app = Flask(__name__)
14
15
16def seed_database() -> None:
17    """Create the articles table and seed rows."""
18    with config.provide_session() as session:
19        session.execute(CREATE_ARTICLES)
20        for row in ARTICLES:
21            session.execute(
22                SQL(
23                    """
24                    INSERT OR REPLACE INTO articles (id, title, body)
25                    VALUES (:id, :title, :body)
26                    """
27                ),
28                row,
29            )
30
31
32@app.get("/articles")
33def list_articles() -> "Response":
34    """Return the article dataset as JSON."""
35    with config.provide_session() as session:
36        result = session.execute("SELECT id, title, body FROM articles ORDER BY id")
37        return jsonify(result.all())
38
39
40def main() -> None:
41    """Seed the database without starting Flask."""
42    seed_database()
43
44
45if __name__ == "__main__":
46    main()
47
48
49# Seed eagerly so importing the module for smoke tests prepares the dataset.
50seed_database()