241 lines
6.0 KiB
Markdown
241 lines
6.0 KiB
Markdown
# 同步架构设计
|
||
|
||
## 概述
|
||
|
||
Flask 是一个基于 WSGI 的同步 Web 框架,采用同步编程模型。本文档介绍项目的同步架构设计及其优势。
|
||
|
||
:::tip 为什么选择同步架构?
|
||
1. **成熟稳定**:Flask 的同步模型经过长期验证,稳定可靠
|
||
2. **易于理解**:同步编程模型更直观,易于调试和维护
|
||
3. **工具完善**:Flask 生态完善,各种扩展和工具支持良好
|
||
4. **部署简单**:WSGI 标准,支持多种部署方式
|
||
:::
|
||
|
||
## 同步模型特性
|
||
|
||
| 特性 | 说明 |
|
||
|:-----|:-----|
|
||
| 编程模型 | 同步 `def` |
|
||
| 并发处理 | 多线程/多进程(由 WSGI 服务器管理) |
|
||
| I/O 等待 | 阻塞当前线程,其他线程不受影响 |
|
||
| 学习曲线 | 平缓,标准 Python 编程 |
|
||
| 调试难度 | 简单,标准 pdb 调试 |
|
||
| 生态支持 | 完善,Flask 扩展生态丰富 |
|
||
|
||
## Flask 同步模型
|
||
|
||
### 请求处理流程
|
||
|
||
```
|
||
客户端请求
|
||
↓
|
||
WSGI 服务器(Gunicorn)
|
||
↓
|
||
Flask 应用
|
||
↓
|
||
中间件链(before_request)
|
||
↓
|
||
路由分发(Blueprint)
|
||
↓
|
||
视图函数(Router)
|
||
↓
|
||
Service 层
|
||
↓
|
||
Repository 层
|
||
↓
|
||
SQLAlchemy ORM
|
||
↓
|
||
数据库
|
||
↓
|
||
返回响应
|
||
```
|
||
|
||
### 多线程/多进程
|
||
|
||
Flask 通过 WSGI 服务器(如 Gunicorn)实现并发处理:
|
||
|
||
```bash
|
||
# 使用 Gunicorn 启动,4 个工作进程,每个进程 4 个线程
|
||
gunicorn -w 4 -t 4 app:app
|
||
```
|
||
|
||
| 参数 | 说明 |
|
||
|:-----|:-----|
|
||
| `-w 4` | 4 个工作进程 |
|
||
| `-t 4` | 每个进程 4 个线程 |
|
||
| `app:app` | Flask 应用实例 |
|
||
|
||
## 同步代码示例
|
||
|
||
### Service 层
|
||
|
||
```python
|
||
# src/modules/system/position/service.py
|
||
from src.common.base_service import BaseService
|
||
from src.core.exceptions import BizError
|
||
from src.modules.system.position.schema import PositionForm, PositionStatusForm
|
||
from src.modules.system.position.repository import PositionRepository
|
||
from src.modules.system.user.repository import UserRepository
|
||
|
||
|
||
class PositionService(BaseService):
|
||
"""
|
||
岗位服务类
|
||
|
||
所有方法均为同步 classmethod,通过 Repository 访问数据库。
|
||
"""
|
||
repository = PositionRepository
|
||
form = PositionForm
|
||
status_form = PositionStatusForm
|
||
model_name = "岗位"
|
||
|
||
@classmethod
|
||
def before_delete(cls, ids):
|
||
"""删除前校验:检查用户引用"""
|
||
for pid in ids:
|
||
if UserRepository.count_by({'position_id': pid}) > 0:
|
||
raise BizError(f"岗位ID {pid} 已被用户引用,无法删除")
|
||
```
|
||
|
||
### Repository 层
|
||
|
||
```python
|
||
# src/modules/system/position/repository.py
|
||
from src.common.base_repository import BaseRepository
|
||
from src.common.constants.common import PAGE_SIZE
|
||
from src.modules.system.position.models import Position
|
||
|
||
|
||
class PositionRepository(BaseRepository):
|
||
"""岗位数据仓储"""
|
||
model = Position
|
||
|
||
@classmethod
|
||
def page(cls, params: dict):
|
||
"""分页查询:同步调用基类 find_page"""
|
||
return cls.find_page(
|
||
page=int(params.get('pageNo', 1)),
|
||
page_size=int(params.get('pageSize', PAGE_SIZE)),
|
||
filters={'status': params.get('status')},
|
||
like_filters={'name': params.get('name')},
|
||
order_by='sort',
|
||
)
|
||
|
||
@classmethod
|
||
def list_enabled(cls, params=None):
|
||
"""查询启用的岗位列表"""
|
||
params = params or {}
|
||
return cls.find_list(
|
||
filters={'status': 1},
|
||
like_filters={'name': params.get('name')},
|
||
order_by='sort',
|
||
)
|
||
```
|
||
|
||
## 同步架构优势
|
||
|
||
### 1. 代码简洁
|
||
|
||
同步代码更直观,易于理解和维护:
|
||
|
||
```python
|
||
# 同步代码(本项目)
|
||
from src.modules.system.position.service import get_position_page
|
||
|
||
def page():
|
||
"""同步调用 service"""
|
||
return R.ok(data=get_position_page(request.args))
|
||
```
|
||
|
||
### 2. 调试简单
|
||
|
||
同步代码的调试更简单,标准 Python 调试工具直接可用:
|
||
|
||
```python
|
||
# 同步调试:直接使用 pdb
|
||
import pdb; pdb.set_trace()
|
||
```
|
||
|
||
### 3. 生态完善
|
||
|
||
Flask 生态完善,各种扩展支持良好:
|
||
|
||
| 扩展 | 用途 |
|
||
|:-----|:-----|
|
||
| Flask-SQLAlchemy | ORM 集成 |
|
||
| Flask-Migrate | 数据库迁移 |
|
||
| Flask-CORS | 跨域资源共享 |
|
||
| Flask-WTF | 表单校验(WTForms 集成) |
|
||
| redis-py | Redis 同步客户端 |
|
||
| APScheduler | 定时任务调度 |
|
||
|
||
### 4. 部署简单
|
||
|
||
WSGI 标准,支持多种部署方式:
|
||
|
||
```bash
|
||
# Gunicorn(推荐)
|
||
gunicorn -w 4 -t 4 app:app
|
||
|
||
# uWSGI
|
||
uwsgi --http 0.0.0.0:8021 --wsgi-file app.py --callable app
|
||
|
||
# Flask 内置服务器(仅开发)
|
||
python app.py
|
||
```
|
||
|
||
## 性能优化
|
||
|
||
### 1. 连接池
|
||
|
||
SQLAlchemy 使用连接池管理数据库连接:
|
||
|
||
```python
|
||
from sqlalchemy import create_engine
|
||
|
||
engine = create_engine(
|
||
DB_URL,
|
||
pool_size=10, # 连接池大小
|
||
max_overflow=20, # 最大溢出连接数
|
||
pool_recycle=3600, # 连接回收时间(秒)
|
||
)
|
||
```
|
||
|
||
### 2. 缓存
|
||
|
||
使用 Redis 缓存热点数据:
|
||
|
||
```python
|
||
def get_position_list(self):
|
||
"""获取岗位列表(带缓存)"""
|
||
cache_key = "position:list"
|
||
cached = redis.get(cache_key)
|
||
if cached:
|
||
return json.loads(cached)
|
||
|
||
# 查询数据库
|
||
positions = cls.repository.find_list(filters={'status': 1})
|
||
result = [p.to_dict() for p in positions]
|
||
|
||
# 写入缓存
|
||
redis.set(cache_key, json.dumps(result), ex=3600)
|
||
return result
|
||
```
|
||
|
||
### 3. 定时任务
|
||
|
||
项目使用 APScheduler 实现定时任务调度,任务定义存储在数据库中:
|
||
|
||
```python
|
||
# src/core/scheduler.py
|
||
from apscheduler.schedulers.background import BackgroundScheduler
|
||
|
||
scheduler = BackgroundScheduler()
|
||
```
|
||
|
||
定时任务在独立线程中执行,不阻塞主请求处理流程。支持 Cron、Interval、Date 三种触发器,通过 Redis 实现多实例互斥,避免重复执行。
|
||
|
||
## 总结
|
||
|
||
项目采用 Flask 同步架构,具有成熟稳定、易于理解、工具完善、部署简单等优势。对于后台管理系统这类以 CRUD 为主的场景,同步模型完全够用,代码更简洁,调试更方便。通过连接池、Redis 缓存、APScheduler 定时任务等技术,可以进一步优化性能。
|