-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
91 lines (74 loc) · 2.61 KB
/
main.py
File metadata and controls
91 lines (74 loc) · 2.61 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import os
import shutil
from uuid import uuid4
from fastapi import FastAPI, Request, Form, UploadFile, File
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from app.db import SessionLocal, engine
from app.models import User
from app.crud import (
get_users_from_db,
get_users_from_redis,
cache_users,
create_user as create_user_in_db,
)
import redis.asyncio as redis
app = FastAPI()
# Mount static files (e.g., uploaded avatars)
app.mount("/static", StaticFiles(directory="app/static"), name="static")
templates = Jinja2Templates(directory="app/templates")
# Redis client will be created on startup
redis_client = None
@app.on_event("startup")
async def startup():
global redis_client
redis_client = redis.Redis(
host=os.getenv("REDIS_HOST"),
port=int(os.getenv("REDIS_PORT")),
decode_responses=True,
)
async with engine.begin() as conn:
await conn.run_sync(User.metadata.create_all)
@app.get("/", response_class=HTMLResponse)
async def get_users(request: Request):
cached = await get_users_from_redis(redis_client)
if cached:
return templates.TemplateResponse(
"users.html", {"request": request, "users": cached, "dataSource": "redis"}
)
async with SessionLocal() as session:
users = await get_users_from_db(session)
users_dicts = [
{
"name": u.name,
"email": u.email,
"avatarPath": u.avatar_path,
"status": "loaded from DB",
}
for u in users
]
await cache_users(redis_client, users_dicts)
return templates.TemplateResponse(
"users.html",
{"request": request, "users": users_dicts, "dataSource": "postgres"},
)
@app.post("/", response_class=HTMLResponse)
async def create_user(
request: Request,
name: str = Form(...),
email: str = Form(...),
avatar: UploadFile = File(None),
):
avatar_path = None
if avatar:
ext = os.path.splitext(avatar.filename)[1]
avatar_filename = f"{uuid4().hex}{ext}"
avatar_path = f"/static/uploads/{avatar_filename}"
full_path = f"app/static/uploads/{avatar_filename}"
with open(full_path, "wb") as buffer:
shutil.copyfileobj(avatar.file, buffer)
async with SessionLocal() as session:
await create_user_in_db(session, name, email, avatar_path)
await redis_client.delete("cached_users") # Invalidate cache
return RedirectResponse("/", status_code=303)