-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
89 lines (69 loc) · 2.39 KB
/
main.py
File metadata and controls
89 lines (69 loc) · 2.39 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 fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from models import Product
from database import session, engine
import database_models
from sqlalchemy.orm import Session
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins = ["http://localhost:3000"],
allow_methods = ["*"]
)
database_models.Base.metadata.create_all(bind = engine)
@app.get("/")
def greet():
return("Hello, World!")
products = [
Product(id = 1, name = "Phone", description = "Budget Phones",price = 9999, quantity = 10),
Product(id = 2, name= "Laptop", description = "Budget Laptop", price = 59999, quantity = 5)
]
def get_db():
db = session()
try:
yield db
finally:
db.close()
def init_db():
db = session()
count = db.query(database_models.Product).count
if count == 0:
for product in products:
db.add(database_models.Product(**product.model_dump()))
db.commit()
init_db()
@app.get("/products")
def get_all_products(db: Session = Depends(get_db)):
db_products = db.query(database_models.Product).all()
return db_products
@app.get("/products/{id}")
def get_product_by_id(id: int, db: Session = Depends(get_db)):
db_product = db.query(database_models.Product).filter(database_models.Product.id == id).first()
if db_product:
return db_product
return "product not found"
@app.post("/products")
def add_product(product: Product, db: Session = Depends(get_db)):
db.add(database_models.Product(**product.model_dump()))
db.commit()
return product
@app.put("/products/{id}")
def update_product(id: int, product: Product, db: Session = Depends(get_db)):
db_product = db.query(database_models.Product).filter(database_models.Product.id == id).first()
if db_product:
db_product.name = product.name
db_product.description = product.description
db_product.price = product.price
db_product.quantity = product.quantity
db.commit()
return "Product updated"
else:
return "No products found"
@app.delete("/products/{id}")
def delete_product(id: int, db: Session = Depends(get_db)):
db_product = db.query(database_models.Product).filter(database_models.Product.id == id).first()
if db_product:
db.delete(db_product)
db.commit()
else:
return "Products not found"