#!/usr/bin/env python3 """ HuggingRun hard example: FastAPI + SQLite with persistence in PERSIST_PATH. Run with: RUN_CMD=uvicorn app.fastapi_sqlite:app --host 0.0.0.0 --port 7860 """ import os from pathlib import Path from fastapi import FastAPI from fastapi.responses import HTMLResponse import sqlite3 app = FastAPI(title="HuggingRun FastAPI+SQLite") DB_PATH = Path(os.environ.get("PERSIST_PATH", "/data")) / "huggingrun.db" def get_visits(): DB_PATH.parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(str(DB_PATH)) conn.execute("CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY, count INTEGER)") conn.commit() n = conn.execute("SELECT COALESCE(SUM(count), 0) FROM visits").fetchone()[0] conn.close() return n def inc_visits(): DB_PATH.parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(str(DB_PATH)) conn.execute("CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY, count INTEGER)") conn.execute("INSERT INTO visits (count) VALUES (1)") conn.commit() n = conn.execute("SELECT COALESCE(SUM(count), 0) FROM visits").fetchone()[0] conn.close() return n @app.get("/", response_class=HTMLResponse) def root(): n = inc_visits() return f"""
Hard example: FastAPI + SQLite. DB path: {DB_PATH}
Total visits (persisted): {n}
""" @app.get("/api") def api(): n = get_visits() return {"message": "HuggingRun FastAPI+SQLite", "total_visits": n}