File size: 1,748 Bytes
a3bfafd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/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"""<!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>"""


@app.get("/api")
def api():
    n = get_visits()
    return {"message": "HuggingRun FastAPI+SQLite", "total_visits": n}