first commit
This commit is contained in:
0
app/routes/__init__.py
Normal file
0
app/routes/__init__.py
Normal file
BIN
app/routes/__pycache__/__init__.cpython-313.pyc
Normal file
BIN
app/routes/__pycache__/__init__.cpython-313.pyc
Normal file
Binary file not shown.
BIN
app/routes/__pycache__/items.cpython-313.pyc
Normal file
BIN
app/routes/__pycache__/items.cpython-313.pyc
Normal file
Binary file not shown.
61
app/routes/items.py
Normal file
61
app/routes/items.py
Normal file
@@ -0,0 +1,61 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class Item(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
price: float
|
||||
in_stock: bool = True
|
||||
|
||||
# 模拟数据
|
||||
items_db = [
|
||||
Item(id=1, name="商品1", description="这是商品1", price=99.99, in_stock=True),
|
||||
Item(id=2, name="商品2", description="这是商品2", price=199.99, in_stock=False),
|
||||
Item(id=3, name="商品3", price=299.99, in_stock=True),
|
||||
]
|
||||
|
||||
@router.get("/items", response_model=List[Item])
|
||||
def get_all_items():
|
||||
"""获取所有商品"""
|
||||
return items_db
|
||||
|
||||
@router.get("/items/{item_id}", response_model=Item)
|
||||
def get_item(item_id: int):
|
||||
"""根据ID获取商品"""
|
||||
for item in items_db:
|
||||
if item.id == item_id:
|
||||
return item
|
||||
raise HTTPException(status_code=404, detail="商品未找到")
|
||||
|
||||
@router.post("/items", response_model=Item)
|
||||
def create_item(item: Item):
|
||||
"""创建新商品"""
|
||||
# 检查ID是否已存在
|
||||
for existing_item in items_db:
|
||||
if existing_item.id == item.id:
|
||||
raise HTTPException(status_code=400, detail="商品ID已存在")
|
||||
|
||||
items_db.append(item)
|
||||
return item
|
||||
|
||||
@router.put("/items/{item_id}", response_model=Item)
|
||||
def update_item(item_id: int, item: Item):
|
||||
"""更新商品"""
|
||||
for index, existing_item in enumerate(items_db):
|
||||
if existing_item.id == item_id:
|
||||
items_db[index] = item
|
||||
return item
|
||||
raise HTTPException(status_code=404, detail="商品未找到")
|
||||
|
||||
@router.delete("/items/{item_id}")
|
||||
def delete_item(item_id: int):
|
||||
"""删除商品"""
|
||||
for index, item in enumerate(items_db):
|
||||
if item.id == item_id:
|
||||
del items_db[index]
|
||||
return {"message": "商品已删除"}
|
||||
raise HTTPException(status_code=404, detail="商品未找到")
|
||||
Reference in New Issue
Block a user