File size: 2,137 Bytes
fbd1869 |
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 |
from typing import Optional
from fastapi import FastAPI, status, Response, HTTPException
from pydantic import BaseModel
from random import randrange
class po(BaseModel):
title:str
content:str
rating:Optional[int]=None
db = [
{"title":"Title 1","content":"Content 1","id":1},
{"title":"Title 2","content":"Content 2","id":2},
{"title":"Title 3","content":"Content 3","id":3},
{"title":"Title 4","content":"Content 4","id":4},
{"title":"Title 5","content":"Content 5","id":5}
]
def find_id(id):
for i in db:
if i["id"] == id:
return i
def find_index_post(id):
for i, p in enumerate(db):
if p["id"] == id:
print(p)
print(i)
return i
app = FastAPI()
@app.get("/post")
async def all_podt():
return {"Message":db}
@app.post("/post",status_code=status.HTTP_201_CREATED)
async def creat_post(post:po):
post_dict = post.dict()
post_dict['id']= randrange(1,500000)
db.append(post_dict)
return{"New Post":post_dict}
@app.get("/post/latests") #Recent Post
async def latests_post():
post = db[len(db)-1]
return {"Message": post}
@app.get("/post/{id}")
async def post_by_id(id:int, res:Response):
post = find_id(id)
if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post with id {id} not found.")
else:
return{"Post": post}
@app.delete("/post/{id}",status_code=status.HTTP_204_NO_CONTENT)
async def delete_post(id:int):
index = find_index_post(id)
if index is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f"Data not found.")
db.append(index)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@app.put("/post/{id}")
async def update_post(id:int,post:po):
index = find_index_post(id)
if index in None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Data not found")
post_dict = post.dict()
post_dict['id'] = id
db[index] = post_dict
return {"Data":db[index]}
# venv\Scripts\activate.bat
# python -m uvicorn app.mainTest:app --reload |