-
Notifications
You must be signed in to change notification settings - Fork 33
/
main.py
71 lines (55 loc) · 2.24 KB
/
main.py
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
import uuid
from fastapi import Depends
from fastapi import FastAPI, Form
from fastapi import Request, Response
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from database import Base
from database import SessionLocal
from database import engine
from models import create_todo
from models import delete_todo
from models import get_todo
from models import get_todos
from models import update_todo
Base.metadata.create_all(bind=engine)
app = FastAPI()
templates = Jinja2Templates(directory="templates")
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/", response_class=HTMLResponse)
def home(request: Request, db: Session = Depends(get_db)):
session_key = request.cookies.get("session_key", uuid.uuid4().hex)
todos = get_todos(db, session_key)
context = {
"request": request,
"todos": todos,
"title": "Home"
}
response = templates.TemplateResponse("home.html", context)
response.set_cookie(key="session_key", value=session_key, expires=259200) # 3 days
return response
@app.post("/add", response_class=HTMLResponse)
def post_add(request: Request, content: str = Form(...), db: Session = Depends(get_db)):
session_key = request.cookies.get("session_key")
todo = create_todo(db, content=content, session_key=session_key)
context = {"request": request, "todo": todo}
return templates.TemplateResponse("todo/item.html", context)
@app.get("/edit/{item_id}", response_class=HTMLResponse)
def get_edit(request: Request, item_id: int, db: Session = Depends(get_db)):
todo = get_todo(db, item_id)
context = {"request": request, "todo": todo}
return templates.TemplateResponse("todo/form.html", context)
@app.put("/edit/{item_id}", response_class=HTMLResponse)
def put_edit(request: Request, item_id: int, content: str = Form(...), db: Session = Depends(get_db)):
todo = update_todo(db, item_id, content)
context = {"request": request, "todo": todo}
return templates.TemplateResponse("todo/item.html", context)
@app.delete("/delete/{item_id}", response_class=Response)
def delete(item_id: int, db: Session = Depends(get_db)):
delete_todo(db, item_id)