FASTAPI+VUE3平价商贸管理系统
一、项目概述
PJMall 是一个基于 FastAPI 构建的商城管理系统后端服务,提供商品管理、订单处理、用户认证等核心功能。系统采用分层架构设计,支持高并发访问,适用于多角色用户(管理员、客户、供应商)。
核心特性
- 🚀 高性能:基于 FastAPI 异步框架,支持每秒数千次请求
- 🔐 安全认证:JWT+RBAC 权限控制体系
- 📦 标准化接口:自动生成 Swagger API 文档
- 📊 数据分析:多维度销售统计分析模块
- ⚡️方便快捷:上手快搭,建迅速
二、后端技术架构设计
1. 技术栈
层级 | 技术选型 | 版本号 |
---|---|---|
开发框架 | FastAPI | v0.112.2 |
ORM | SQLAlchemy | 1.4.48 |
数据库 | MySQL | 8.0+ |
认证 | PyJWT | 2.9.0 |
服务器 | Uvicorn | 0.30.1 |
2. 分层架构
myapi/
├── api/ # API路由层 (FastAPI Router)
├── models/ # 数据模型层 (SQLAlchemy)
├── config/ # 系统配置层
│ ├── database.py # 数据库配置
│ ├── my_jwt.py # JWT认证
│ └── logger.py # 日志系统
└── utils/ # 工具类
核心模块实现
1. 用户认证系统
# config/my_jwt.py
def generate_token(data: dict):# 设置30分钟过期时间expire = datetime.utcnow() + timedelta(minutes=30)data.update({"exp": expire})return jwt.encode(payload=data,key=config.SECRET_KEY,algorithm=config.ALGORITHM)# api/base.py
@base_router.post("/login")
async def login(request: Request):data = await request.json()user = authenticate_user(data["username"], data["password"])if not user:raise HTTPException(status_code=400, detail="认证失败")return {"token": generate_token({"username": user.username,"role": user.role})}
2. 商品管理模块
典型的功能实现:
# api/product.py
@product_router.get("/search")
async def search_products(request: Request,q: str = "", brand: str = None,category: str = None
):"""支持多条件商品搜索"""query = session.query(Product)if q:query = query.filter(Product.name.like(f"%{q}%"))if brand:query = query.filter_by(brand=brand)# ...其他过滤条件return paginate(query)# models/Product.py
class Product(Base):__tablename__ = 'product'id = Column(Integer, primary_key=True)name = Column(String(255), index=True) # 添加索引提升查询速度price = Column(Numeric(10,2)) # 精确小数处理status = Column(String(20), default="ON_SALE")
3. 订单业务处理
典型订单创建流程:
数据库线程池
数据库优化
# config/database.py
engine = create_engine(os.getenv("DB_URL"),pool_size=10, # 连接池大小max_overflow=20, # 最大溢出连接pool_pre_ping=True, # 连接健康检查pool_recycle=3600 # 1小时回收连接
)
开发注意事项
环境配置
# 安装依赖
pip install -r requirements.txt
# 启动开发服务器
uvicorn main:app --reload --port 8000
常见问题
🚫 JWT令牌过期:客户端需实现自动刷新
💾 数据库连接泄漏:确保session及时关闭
🐛 并发问题:敏感操作需加锁处理
二、前端介绍
一、核心模块实现
1. 用户认证系统
// src/utils/utils.js - JWT解码实现
import jwtDecode from 'jwt-decode';
export const getTokenInfo = (token) => {try {return jwtDecode(token);} catch (error) {console.error('Invalid token:', error);return null;}
}
安全实践:使用
sessionStorage
替代localStorage
// src/store/index.js
state: {token: sessionStorage.getItem('token') || null
}
2. 商品管理体系
<!-- src/views/productManage/productManage.vue - 懒加载组件 -->
<template><component :is="currentTabComponent" v-if="currentTabComponent" />
</template><script setup>
const currentTabComponent = ref(null);
const loadComponent = async (tab) => {currentTabComponent.value = await import(`../components/${tab}.vue`);
}
</script>
二、组件架构
1. 可复用组件库
<!-- src/components/Header.vue - 响应式布局 -->
<template><header class="app-header"><div class="logo">PingJia Mall</div><nav class="nav-menu"><!-- 响应式导航实现 --></nav></header>
</template>
2. 图标系统
<!-- src/components/icons/IconDocumentation.vue -->
<template><svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M14 2H6C4.89 2 4 2.9 4 4V20C4 21.1 4.89 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" /></svg>
</template>
三、路由与状态管理
1. 动态路由配置
// src/routers/index.js
const routes = [{path: '/product',name: 'Product',component: () => import('../views/productManage/productManage.vue'),meta: { requiresAuth: true }}
]
2. Vuex状态管理
// src/store/index.js
const store = new Vuex.Store({modules: {user: {state: { profile: null },mutations: { SET_PROFILE(state, profile) { state.profile = profile } }},cart: {state: { items: [] },actions: { addToCart({ commit }, item) { /* ... */ } }}}
})
四、API架构
1. 接口分层设计
// src/api/financial.js - 财务模块API
import request from '@/utils/request';export default {getRevenueStats: () => request.get('/api/finance/revenue'),exportReport: (params) => request.get('/api/finance/export', { params })
}
2. 请求拦截器
// src/utils/request.js
const service = axios.create({baseURL: process.env.VUE_APP_API_BASE_URL,timeout: 5000
});service.interceptors.request.use(config => {const token = store.state.token;if (token) config.headers['Authorization'] = `Bearer ${token}`;return config;
});
五、构建配置
1. Vite基础配置
// vite.config.js
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';export default defineConfig({plugins: [vue(),AutoImport({ /* 自动导入配置 */ })]
})
2. Webpack兼容配置
// webpack.config.js
module.exports = {entry: './src/main.js',output: {filename: 'bundle.js',path: path.resolve(__dirname, 'dist')},module: {rules: [{test: \/\.vue$/,loader: 'vue-loader'}]}
}
四、系统功能界面
文档
采购
采购详情
采购编辑
采购详情
客户管理
供应商管理
分类管理
品牌管理
商品管理
用户管理–管理员可见
看板