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.adapters.sqlite import SqliteConfig
 8from sqlspec.core import SQL
 9
10__all__ = ("list_articles", "main", "seed_database")
11
12
13registry = sqlite_registry()
14config = registry.get_config(SqliteConfig)
15app = Flask(__name__)
16
17
18def seed_database() -> None:
19    """Create the articles table and seed 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@app.get("/articles")
35def list_articles() -> "Response":
36    """Return the article dataset as JSON."""
37    with config.provide_session() as session:
38        result = session.execute("SELECT id, title, body FROM articles ORDER BY id")
39        return jsonify(result.all())
40
41
42def main() -> None:
43    """Seed the database without starting Flask."""
44    seed_database()
45
46
47if __name__ == "__main__":
48    main()
49
50
51# Seed eagerly so importing the module for smoke tests prepares the dataset.
52seed_database()