Python Web 开发实战:构建 FastAPI 在线商店系统
目录
- 🛍️ 商品管理
- 🛒 购物车与结算
- 💳 支付集成(模拟支付)
- ⚙️ 系统拓展与优化建议
🛍️ 1. 商品管理
商品管理是任何在线商店系统的核心功能,主要包括商品的添加、编辑、删除和查询。在 FastAPI 中,商品管理的实现通常包括定义商品的数据模型、创建 API 端点来处理商品的增、删、改、查操作,并且对请求数据进行验证和格式化。
1.1 商品数据模型
商品模型是整个商店系统中最基础的数据结构,包含了商品的各种信息,例如名称、价格、库存数量和描述等。使用 Pydantic 定义商品模型,并确保所有传入数据的类型和结构符合要求。
from pydantic import BaseModel
from typing import Optional
class Product(BaseModel):
name: str
description: str
price: float
stock: int
image_url: Optional[str] = None # 商品图片链接,非必填项
1.2 商品管理 API 设计
接下来,我们设计几个 API 端点来处理商品的增、删、改、查操作。通过这些端点,商店管理员可以管理商品信息。
1.2.1 创建商品
该 API 用于商店管理员添加新商品。通过 POST
请求提交商品信息,FastAPI 会自动验证数据并将其保存到数据库。
from fastapi import FastAPI, HTTPException
app = FastAPI()
# 模拟商品数据库
product_db = {}
@app.post("/add_product/")
async def add_product(product: Product):
product_id = len(product_db) + 1 # 使用商品数作为 ID
product_db[product_id] = product.dict()
return {"message": "Product added successfully", "product_id": product_id}
1.2.2 编辑商品
编辑商品时,管理员可以通过商品 ID 更新其信息。对于已存在的商品,系统将会更新相关的字段。
@app.put("/update_product/{product_id}")
async def update_product(product_id: int, product: Product):
if product_id not in product_db:
raise HTTPException(status_code=404, detail="Product not found")
product_db[product_id].update(product.dict())
return {"message": "Product updated successfully"}
1.2.3 删除商品
删除商品的 API 通过商品 ID 将其从商品数据库中移除。
@app.delete("/delete_product/{product_id}")
async def delete_product(product_id: int):
if product_id not in product_db:
raise HTTPException(status_code=404, detail="Product not found")
del product_db[product_id]
return {"message": "Product deleted successfully"}
1.2.4 查询商品
通过 GET 请求,用户或管理员可以查询某个商品的信息或列出所有商品。以下代码提供了两种查询方式:根据商品 ID 查询,和查询所有商品。
@app.get("/get_product/{product_id}")
async def get_product(product_id: int):
if product_id not in product_db:
raise HTTPException(status_code=404, detail="Product not found")
return product_db[product_id]
@app.get("/get_all_products/")
async def get_all_products():
return product_db
通过这些 API,商店管理员可以非常方便地管理商品信息。
🛒 2. 购物车与结算
购物车是在线商店系统的重要组成部分,用户可以将商品加入购物车并进行结算。结算时会计算总价,并生成订单。该模块主要包括购物车的添加、查看和结算功能。
2.1 购物车数据模型
购物车由商品和数量组成,每个用户拥有一个独立的购物车。购物车模型需要记录商品 ID 和对应的数量。
class CartItem(BaseModel):
product_id: int
quantity: int
class ShoppingCart(BaseModel):
items: dict[int, CartItem] # 商品ID映射到购物车项
total_price: float = 0.0 # 总价格,系统自动计算
2.2 添加商品到购物车
通过该 API,用户可以将商品添加到购物车。如果该商品已经在购物车中,系统会更新其数量。
@app.post("/add_to_cart/{user_id}")
async def add_to_cart(user_id: int, cart_item: CartItem):
cart = shopping_carts.get(user_id, ShoppingCart(items={}))
if cart_item.product_id in cart.items:
cart.items[cart_item.product_id].quantity += cart_item.quantity
else:
cart.items[cart_item.product_id] = cart_item
cart.total_price = sum(item.quantity * product_db[item.product_id]["price"] for item in cart.items.values())
shopping_carts[user_id] = cart
return {"message": "Item added to cart", "total_price": cart.total_price}
2.3 查看购物车
用户可以查询自己购物车中的所有商品以及总价。以下是查看购物车内容的接口。
@app.get("/view_cart/{user_id}")
async def view_cart(user_id: int):
cart = shopping_carts.get(user_id, ShoppingCart(items={}))
return {"items": cart.items, "total_price": cart.total_price}
2.4 结算购物车
结算时,系统会计算购物车内所有商品的总价并生成订单。以下代码展示了结算过程。
@app.post("/checkout/{user_id}")
async def checkout(user_id: int):
cart = shopping_carts.get(user_id)
if not cart or len(cart.items) == 0:
raise HTTPException(status_code=400, detail="Cart is empty")
order_id = len(orders_db) + 1
order = {
"user_id": user_id,
"items": cart.items,
"total_price": cart.total_price,
"status": "pending"
}
orders_db[order_id] = order
shopping_carts[user_id] = ShoppingCart(items={}) # 清空购物车
return {"message": "Checkout successful", "order_id": order_id}
💳 3. 支付集成(模拟支付)
支付功能是电子商务平台的关键环节,通常与第三方支付平台(如支付宝、微信支付、Stripe 等)集成。在此示例中,我们将实现一个模拟支付接口,模拟支付成功和失败的场景。
3.1 支付数据模型
模拟支付时,系统需要一个支付请求的数据模型,包含订单 ID 和支付金额。
class PaymentRequest(BaseModel):
order_id: int
amount: float
3.2 模拟支付接口
此接口将模拟支付过程,支付成功时返回支付成功的消息,支付失败时返回失败的消息。
@app.post("/process_payment/")
async def process_payment(payment: PaymentRequest):
order = orders_db.get(payment.order_id)
if not order:
raise HTTPException(status_code=404, detail="Order not found")
if order["total_price"] != payment.amount:
raise HTTPException(status_code=400, detail="Payment amount mismatch")
# 模拟支付成功
order["status"] = "paid"
return {"message": "Payment successful", "order_status": order["status"]}
3.3 支付状态查询
用户可以查询订单的支付状态。支付状态包含:待支付、已支付、支付失败等。
@app.get("/order_status/{order_id}")
async def order_status(order_id: int):
order = orders_db.get(order_id)
if not order:
raise HTTPException(status_code=404, detail="Order not found")
return {"order_id": order_id, "status": order["status"]}
通过这些模拟支付的 API,用户可以进行虚拟支付操作,查看支付状态,并完成整个购买流程。
⚙️ 4. 系统拓展与优化建议
虽然基本的在线商店系统已经搭建完成,但仍然有多个方面可以进一步优化和拓展:
- 数据库持久化:目前的系统数据保存在内存中,实际应用中需要使用数据库(如 PostgreSQL、MySQL 或 MongoDB)来持久化数据。
- 用户注册与认证:用户注册、登录、密码管理等功能尚未实现,可以通过 FastAPI 提供的 OAuth2 认证和 JWT 实现用户认证与授权。
- 支付集成:可以进一步集成真实的支付系统,如 Stripe 或 PayPal,来实现真实支付功能。
- 性能优化:在高并发的情况下,
系统可以使用异步处理、消息队列等方式来提高性能。