Skip to content

About

电商后端项目:FastAPI + MySQL + async SQLAlchemy 模块化单体,包含 JWT 认证、商品、购物车、库存并发控制、下单幂等与模拟支付。

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Saleor FastAPI Backend

一个学习导向的电商后端,使用 FastAPI + MySQL 实现模块化单体。

功能

  • JWT 注册/登录、当前用户、管理员角色
  • 分类、商品、SKU 的公开查询与管理接口
  • 购物车、结算预览、下单事务、订单快照与订单事件
  • 用户订单查询/取消、管理员订单查询与发货
  • 订单超时取消:默认 30 分钟未支付自动取消并释放库存,每 60 秒扫描;可用 ORDER_PAYMENT_TIMEOUT_MINUTES、ORDER_TIMEOUT_SWEEP_SECONDS 调整
  • 库存调整、库存流水、预留/释放/销售确认
  • 模拟支付、模拟退款、重复回调幂等
  • 统一错误响应、请求 ID、Alembic 迁移、独立测试数据库

技术栈

  • Python 3.13 + FastAPI + Pydantic v2
  • SQLAlchemy 2.x async + asyncmy + MySQL 8
  • Alembic 迁移
  • PyJWT + pwdlib(Argon2)
  • pytest + httpx

架构

flowchart LR
    Client --> API[FastAPI /api/v1]
    API --> Auth[auth / users]
    API --> Catalog[catalog]
    API --> Cart[cart]
    API --> Checkout[checkout]
    API --> Orders[orders]
    API --> Inventory[inventory]
    API --> Payments[payments]
    Checkout --> Cart
    Checkout --> Inventory
    Checkout --> Orders
    Auth --> DB[(MySQL 8)]
    Catalog --> DB
    Cart --> DB
    Orders --> DB
    Inventory --> DB
    Payments --> DB

Loading

快速开始(本地)

要求:Python 3.13、MySQL 8。

python -m venv .venv
.venv\Scripts\activate
pip install -e ".[dev]"

Copy-Item .env.example .env
# 编辑 .env:填写 DB_PASSWORD 和 JWT_SECRET_KEY
# 生成密钥:
# .venv\Scripts\python.exe -c "import secrets; print(secrets.token_urlsafe(48))"

# 在 MySQL 中创建数据库:
# CREATE DATABASE saleor_backend CHARACTER SET utf8mb4;

.venv\Scripts\python.exe -m alembic upgrade head
.venv\Scripts\python.exe scripts\seed_roles.py
.venv\Scripts\python.exe -m uvicorn app.main:application --reload

API 文档:http://127.0.0.1:8000/docs

注册一个用户后,可提升为管理员:

.venv\Scripts\python.exe scripts\grant_admin.py user@example.com

Docker

docker compose up --build

在容器内提升管理员:

docker compose exec api python scripts/grant_admin.py user@example.com

如果 python:3.13-slim 构建时缺少编译工具,可把基础镜像改成 python:3.13,或在 Dockerfile 中安装 build-essential。

主要接口

领域 接口
认证 POST /api/v1/auth/register、POST /api/v1/auth/login
用户 GET/PATCH /api/v1/users/me
分类 GET /api/v1/categories;POST/PATCH /api/v1/admin/categories
商品 GET /api/v1/products、GET /api/v1/products/{id};POST/PATCH /api/v1/admin/products
SKU POST /api/v1/admin/products/{id}/variants、PATCH /api/v1/admin/variants/{id}
购物车 GET /api/v1/cart、POST/PATCH/DELETE /api/v1/cart/items
结算/订单 POST /api/v1/checkout/preview、POST /api/v1/checkout/orders(支持 Idempotency-Key)
订单查询 GET /api/v1/orders、GET /api/v1/orders/{id}、POST /api/v1/orders/{id}/cancel
管理员订单 GET /api/v1/admin/orders、GET /api/v1/admin/orders/{id}、POST /api/v1/admin/orders/{id}/fulfill
库存 GET /api/v1/admin/inventory、POST /api/v1/admin/variants/{id}/inventory-adjustments、GET /api/v1/admin/inventory-movements
支付 POST /api/v1/orders/{id}/payments、POST /api/v1/payments/{id}/simulate-result、POST /api/v1/admin/payments/{id}/refund
健康检查 GET /api/v1/health

测试

.venv\Scripts\python.exe -m pytest -q
.venv\Scripts\python.exe -m alembic check

测试会自动重建独立数据库 saleor_backend_test,需要 MySQL 用户有 CREATE / DROP 权限;不会使用开发库 saleor_backend。

关键回归测试:

  • 库存并发:tests/test_inventory_service.py::test_reserve_is_atomic_under_concurrency
  • 购物车并发:tests/test_concurrency.py::test_add_item_same_sku_is_atomic_under_concurrency
  • 下单幂等:tests/test_checkout_api.py::test_create_order_is_idempotent
  • 下单并发幂等:tests/test_concurrency.py::test_create_order_with_same_key_is_atomic_under_concurrency
  • 支付重复回调:tests/test_payments_api.py::test_payment_success_is_idempotent
  • 支付并发状态刷新:tests/test_concurrency.py::test_order_lock_refreshes_status_after_concurrent_cancel
  • 已取消订单不可支付:tests/test_concurrency.py::test_cancelled_order_cannot_be_paid_when_items_have_no_variant
  • 公开目录可见性:tests/test_products_api.py::test_public_products_require_at_least_one_active_variant
  • DEBUG 错误响应:tests/test_main.py::test_application_never_enables_fastapi_debug
  • 多 SKU 下单回滚:tests/test_checkout_api.py::test_create_order_with_multiple_skus_rolls_back_all_reservations
  • 管理员退款:tests/test_payments_api.py::test_admin_can_refund_paid_order
  • 退款幂等:tests/test_payments_api.py::test_refund_is_idempotent
  • 超时取消:tests/test_concurrency.py::test_timeout_cancels_expired_order_and_releases_inventory
  • 超时不取消已支付订单:tests/test_concurrency.py::test_timeout_does_not_cancel_paid_order
  • 超时与支付并发:tests/test_concurrency.py::test_timeout_and_payment_success_only_one_wins

目录结构

app/
├── api/v1/              # 版本化 API 组合根
├── core/                # 配置、日志、异常、请求 ID、安全
├── db/                  # engine、session、依赖
├── models/              # 所有 ORM 模型的统一入口
└── modules/
    ├── auth/
    ├── users/
    ├── catalog/
    ├── cart/
    ├── inventory/
    ├── checkout/
    ├── orders/
    ├── payments/
    └── health/
migrations/              # Alembic
tests/                   # pytest + 独立测试库
scripts/                 # seed_roles、grant_admin
docs/                    # 架构、ADR

设计文档

License

本项目采用 MIT License。

About

电商后端项目:FastAPI + MySQL + async SQLAlchemy 模块化单体,包含 JWT 认证、商品、购物车、库存并发控制、下单幂等与模拟支付。

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages