一、項目概述
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'}]}
}
四、系統功能界面
文檔
采購
采購詳情
采購編輯
采購詳情
客戶管理
供應商管理
分類管理
品牌管理
商品管理
用戶管理–管理員可見
看板