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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
| @app.post("/items/create_item", response_model=ItemResponse, status_code=status.HTTP_201_CREATED, summary="创建商品", description="创建一个新的商品记录") async def create_item(item: ItemCreate, db: AsyncSession = Depends(get_db)): """ 创建新的商品 - **name**: 商品名称(必填) - **description**: 商品描述(可选) - **price**: 商品价格(必须大于等于0) """ try: db_item = Item( name=item.name, description=item.description, price=item.price ) db.add(db_item) await db.commit() await db.refresh(db_item) logger.info(f"商品创建成功: ID={db_item.id}, Name={db_item.name}") return db_item except Exception as e: await db.rollback() logger.error(f"商品创建失败: {str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"创建商品失败: {str(e)}" )
@app.get("/items/read_items", response_model=List[ItemResponse], summary="获取商品列表", description="分页获取所有商品列表") async def read_items( skip: int = Query(0, ge=0, description="跳过记录数"), limit: int = Query(100, ge=1, le=1000, description="每页记录数"), db: AsyncSession = Depends(get_db) ): """ 获取商品列表,支持分页 - **skip**: 跳过的记录数(默认0) - **limit**: 每页记录数(默认100,最大1000) """ try: result = await db.execute( select(Item) .order_by(Item.id) .offset(skip) .limit(limit) ) items = result.scalars().all() count_result = await db.execute(select(func.count()).select_from(Item)) total = count_result.scalar() logger.info(f"获取商品列表成功: 总数={total}, 本次返回={len(items)}") return items except Exception as e: logger.error(f"获取商品列表失败: {str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"读取商品列表失败: {str(e)}" )
@app.get("/items/read_item/{item_id}", response_model=ItemResponse, summary="获取单个商品", description="根据ID获取单个商品的详细信息") async def read_item( item_id: int = Query(..., ge=1, description="商品ID"), db: AsyncSession = Depends(get_db) ): """ 根据ID获取单个商品详情 """ try: item = await db.get(Item, item_id) if item is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="商品不存在" ) logger.info(f"获取商品成功: ID={item_id}") return item except HTTPException: raise except Exception as e: logger.error(f"获取商品失败: ID={item_id}, 错误={str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"读取商品失败: {str(e)}" )
@app.put("/items/update_item/{item_id}", response_model=ItemResponse, summary="更新商品", description="根据ID更新商品信息") async def update_item( item_id: int, item: ItemUpdate, db: AsyncSession = Depends(get_db) ): """ 更新商品信息 支持部分更新,只更新提供的字段 """ try: db_item = await db.get(Item, item_id) if db_item is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="商品不存在" ) update_data = item.dict(exclude_unset=True) for field, value in update_data.items(): if value is not None: setattr(db_item, field, value) db.add(db_item) await db.commit() await db.refresh(db_item) logger.info(f"商品更新成功: ID={item_id}") return db_item except HTTPException: raise except Exception as e: await db.rollback() logger.error(f"商品更新失败: ID={item_id}, 错误={str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"更新商品失败: {str(e)}" )
@app.delete("/items/delete_item/{item_id}", summary="删除商品", description="根据ID删除商品") async def delete_item( item_id: int, db: AsyncSession = Depends(get_db) ): """ 删除指定ID的商品 """ try: db_item = await db.get(Item, item_id) if db_item is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="商品不存在" ) await db.delete(db_item) await db.commit() logger.info(f"商品删除成功: ID={item_id}") return { "message": "商品删除成功", "item_id": item_id, "timestamp": datetime.now().isoformat() } except HTTPException: raise except Exception as e: await db.rollback() logger.error(f"商品删除失败: ID={item_id}, 错误={str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"删除商品失败: {str(e)}" )
|