-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
95 lines (79 loc) · 3.04 KB
/
main.py
File metadata and controls
95 lines (79 loc) · 3.04 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
90
91
92
93
94
95
from fastapi import FastAPI, HTTPException
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import BaseModel, Field
from bson import ObjectId
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins['https://localhost:3000'],
allow_methods['*'],
allow_headers=['*']
)
# MongoDB configuration
MONGO_DB_URL = "mongodb://localhost:27017" # Replace with your MongoDB URI
DATABASE_NAME = "FastAPI"
COLLECTION_NAME = "products"
# Initialize MongoDB client and database
client = AsyncIOMotorClient(MONGO_DB_URL)
db = client[DATABASE_NAME]
products_collection = db[COLLECTION_NAME]
# Pydantic models for request validation
class Product(BaseModel):
name: str
quantity: int
price: float
class ProductResponse(Product):
id: str = Field(alias="_id")
# Helper to convert MongoDB document to Pydantic model
def convert_mongo_to_pydantic(doc):
if doc:
doc["_id"] = str(doc["_id"])
return doc
@app.post("/products/", response_model=ProductResponse)
async def create_or_update_product(product: Product):
"""
Create a new product if it does not exist by name,
or update the quantity and price of an existing product.
"""
try:
# Check if a product with the same name exists
existing_product = await products_collection.find_one({"name": product.name})
if existing_product:
# Update the existing product's quantity and price
new_quantity = existing_product["quantity"] + product.quantity
new_price = product.price # Update with the latest price
updated_product = await products_collection.find_one_and_update(
{"name": product.name},
{"$set": {"quantity": new_quantity, "price": new_price}},
return_document=True
)
return convert_mongo_to_pydantic(updated_product)
else:
# Create a new product
result = await products_collection.insert_one(product.dict())
new_product = await products_collection.find_one({"_id": result.inserted_id})
return convert_mongo_to_pydantic(new_product)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/products/{product_id}", response_model=ProductResponse)
async def get_product(product_id: str):
"""
Get a product by its unique ID.
"""
try:
product = await products_collection.find_one({"_id": ObjectId(product_id)})
if not product:
raise HTTPException(status_code=404, detail="Product not found")
return convert_mongo_to_pydantic(product)
except Exception as e:
raise HTTPException(status_code=400, detail="Invalid product ID")
@app.get("/products/", response_model=list[ProductResponse])
async def list_products():
"""
List all products in the collection.
"""
products = []
async for product in products_collection.find():
products.append(convert_mongo_to_pydantic(product))
return products