-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathles_65_fastApi_templates.py
58 lines (43 loc) · 1.74 KB
/
les_65_fastApi_templates.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
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from typing import List
app = FastAPI()
templates = Jinja2Templates(directory="templates")
users = []
#uvicorn les_65_fastApi_templates:app --reload
class User(BaseModel):
id: int
username: str
age: int
@app.get("/", response_class=HTMLResponse)
async def read_users(request: Request):
return templates.TemplateResponse("users.html", {"request": request, "users": users})
@app.get("/users/{user_id}", response_class=HTMLResponse)
async def get_user(request: Request, user_id: int):
for user in users:
if user.id == user_id:
return templates.TemplateResponse("users.html", {"request": request, "user": user})
raise HTTPException(status_code=404, detail="User was not found")
@app.post("/user/{username}/{age}", response_model=User)
async def create_user(username: str, age: int):
user_id = 1 if not users else users[-1].id + 1
new_user = User(id=user_id, username=username, age=age)
users.append(new_user)
return new_user
@app.put("/user/{user_id}/{username}/{age}", response_model=User)
async def update_user(user_id: int, username: str, age: int):
for user in users:
if user.id == user_id:
user.username = username
user.age = age
return user
raise HTTPException(status_code=404, detail="User was not found")
@app.delete("/user/{user_id}", response_model=User)
async def delete_user(user_id: int):
for user in users:
if user.id == user_id:
users.remove(user)
return user
raise HTTPException(status_code=404, detail="User was not found")