Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
89 lines (72 loc) · 2.26 KB
/
Copy pathserver.py
File metadata and controls
89 lines (72 loc) · 2.26 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
from dataclasses import dataclass, field
from datetime import datetime
import uuid
from fastapi import FastAPI, HTTPException
from fastapi import Request,Response
import math
all_p={}
@dataclass
class Product:
id: str = field(default_factory=lambda: str(uuid.uuid4()))
name: str = ""
description: str = ""
price: float = 0.0
created_at: datetime = field(default_factory=datetime.now)
updated_at: datetime = field(default_factory=datetime.now)
def update(self, arg:dict):
for key, value in arg.items():
if(key=="name"):
self.name=value
if(key=="description"):
self.description=value
if(key=="price"):
self.price=value
self.updated_at = datetime.now()
app=FastAPI()
def creat(data: dict):
p = Product(name=data["name"],description=data["description"],price=data["price"])
all_p[p.id] = p
print(all_p)
return p
@app.post("/products")
async def products(req:Request):
body=await req.json()
if not body.get("name") or not isinstance(body.get("price"), (int, float)):
raise HTTPException(
status_code=400,
detail="Bad Request: 'name' is required and 'price' must be a number"
)
x = creat(body)
return x.__dict__
@app.get("/products")
def products():
return all_p
@app.put("/products/{id}")
async def update_product(id: str, req: Request):
body = await req.json()
# Check if product exists
if id not in all_p:
raise HTTPException(
status_code=404,
detail=f"Product with id '{id}' not found"
)
# Update product
all_p[id].update(body)
return all_p[id]
@app.get("/products/{id}")
def getbyid(id:str):
if id not in all_p:
raise HTTPException(
status_code=404,
detail=f"Product with id '{id}' not found"
)
return all_p[id]
@app.delete("/products/{id}")
def delete(id:str):
if id not in all_p:
raise HTTPException(
status_code=404,
detail=f"Product with id '{id}' not found"
)
all_p.pop(id)
return Response(status_code=204)