-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
72 lines (58 loc) · 1.8 KB
/
main.py
File metadata and controls
72 lines (58 loc) · 1.8 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# main.py
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
ADVICE_URL = "https://api.adviceslip.com/advice"
# Fallback advice if API fails
FALLBACK = {
"id": 0,
"advice": "Stay calm. Even broken APIs deserve empathy."
}
async def fetch_advice():
"""
Fetch a random advice from the public API.
- Returns a dictionary with { id, advice }
- On any failure (HTTP, JSON, timeout), returns FALLBACK
- Ensures consistent JSON format for templates and API
"""
try:
async with httpx.AsyncClient(timeout=10) as client:
response = await client.get(ADVICE_URL)
response.raise_for_status()
data = response.json()
# Format from API: {"slip": {"id":..., "advice": ...}}
if "slip" in data:
return data["slip"]
return FALLBACK
except Exception:
return FALLBACK
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
"""
Render full page with the initial advice.
"""
advice = await fetch_advice()
return templates.TemplateResponse(
"index.html",
{"request": request, "advice": advice}
)
@app.get("/advice", response_class=HTMLResponse)
async def advice_partial(request: Request):
"""
Return only the advice card (HTMX partial).
"""
advice = await fetch_advice()
return templates.TemplateResponse(
"advice_partial.html",
{"request": request, "advice": advice}
)
@app.get("/api/advice")
async def advice_json():
"""
Return raw advice in JSON format.
"""
advice = await fetch_advice()
return JSONResponse(advice)