Team Ai
Modelpublic

WalidAlHassan/FastAPI-CRUD-Operations

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
mainTest.py76 linesDownload Raw Back to app
1from typing import Optional2from fastapi import FastAPI, status, Response, HTTPException3from pydantic import BaseModel4from random import randrange5 6class po(BaseModel):7    title:str8    content:str9    rating:Optional[int]=None10 11db = [12    {"title":"Title 1","content":"Content 1","id":1},13    {"title":"Title 2","content":"Content 2","id":2},14    {"title":"Title 3","content":"Content 3","id":3},15    {"title":"Title 4","content":"Content 4","id":4},16    {"title":"Title 5","content":"Content 5","id":5}17]18 19def find_id(id):20    for i in db:21        if i["id"] == id:22            return i23 24def find_index_post(id):25    for i, p in enumerate(db):26        if p["id"] == id:27            print(p)28            print(i)29            return i 30        31app = FastAPI()32 33@app.get("/post")34async def all_podt():35    return {"Message":db}36 37@app.post("/post",status_code=status.HTTP_201_CREATED)38async def creat_post(post:po):39    post_dict = post.dict()40    post_dict['id']= randrange(1,500000)41    db.append(post_dict)42    return{"New Post":post_dict}43 44@app.get("/post/latests") #Recent Post45async def latests_post():46    post = db[len(db)-1]47    return {"Message": post}48 49@app.get("/post/{id}")50async def post_by_id(id:int, res:Response):51    post = find_id(id)52    if not post:53        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post with id {id} not found.")54    else:55     return{"Post": post}56 57@app.delete("/post/{id}",status_code=status.HTTP_204_NO_CONTENT)58async def delete_post(id:int):59    index = find_index_post(id)60    if index is None:61        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f"Data not found.")62    db.append(index)63    return Response(status_code=status.HTTP_204_NO_CONTENT)64    65@app.put("/post/{id}")66async def update_post(id:int,post:po):67    index = find_index_post(id)68    if index in None:69        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Data not found")70    post_dict = post.dict()71    post_dict['id'] = id72    db[index] = post_dict73    return {"Data":db[index]}74 75# venv\Scripts\activate.bat76# python -m uvicorn app.mainTest:app --reload