Spaces:
Sleeping
Sleeping
| #!/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 | |
| def root(): | |
| n = inc_visits() | |
| return f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>HuggingRun + FastAPI + SQLite</title></head> | |
| <body style="font-family:sans-serif;max-width:600px;margin:2em auto;"> | |
| <h1>Run anything on Hugging Face.</h1> | |
| <p><strong>Hard example:</strong> FastAPI + SQLite. DB path: <code>{DB_PATH}</code></p> | |
| <p><strong>Total visits (persisted):</strong> {n}</p> | |
| </body></html>""" | |
| def api(): | |
| n = get_visits() | |
| return {"message": "HuggingRun FastAPI+SQLite", "total_visits": n} | |