Download app/mainTest.py from WalidAlHassan/FastAPI-CRUD-Operations: direct link, hf CLI and curl.
- Browser
- Download file 2.14 kB
-
https://huggingface.co/WalidAlHassan/FastAPI-CRUD-Operations/resolve/main/app/mainTest.py
- Command line
-
hf download hf://WalidAlHassan/FastAPI-CRUD-Operations/app/mainTest.py
-
curl -L -o mainTest.py https://huggingface.co/WalidAlHassan/FastAPI-CRUD-Operations/resolve/main/app/mainTest.py
2.14 kB
| 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() | |
| async def all_podt(): | |
| return {"Message":db} | |
| 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} | |
| #Recent Post | |
| async def latests_post(): | |
| post = db[len(db)-1] | |
| return {"Message": post} | |
| 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} | |
| 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) | |
| 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 |