架构设计
本文档详细介绍美团店铺数据处理工具的技术架构、设计模式和实现细节。
🏗️ 系统架构概览
整体架构
美团店铺数据处理工具采用改进的MVC模式结合多线程架构,实现了界面与业务逻辑的完全分离。
mermaid
graph TB
subgraph "用户界面层 (View)"
A[gui_fluent.py<br/>主界面程序<br/>1401行]
B[QFluentWidgets<br/>组件库]
C[主题系统<br/>深色/浅色切换]
end
subgraph "控制器层 (Controller)"
D[gui_processor.py<br/>GUI专用处理器]
E[ProcessorThread<br/>后台处理线程]
F[FileMonitorThread<br/>文件监控线程]
end
subgraph "业务逻辑层 (Model)"
G[malatang_processor.py<br/>数据处理核心<br/>443行]
H[DataExtractor<br/>数据提取组件]
I[ExcelManager<br/>Excel管理组件]
J[ImageDownloader<br/>图片下载组件]
end
subgraph "配置管理层"
K[config.py<br/>配置文件]
L[requirements.txt<br/>依赖管理]
end
subgraph "数据存储层"
M[Excel文件<br/>malatang_products.xlsx]
N[图片目录<br/>images/]
O[日志文件<br/>malatang_processor.log]
end
A --> D
A --> E
A --> F
D --> G
E --> H
E --> I
E --> J
G --> H
G --> I
G --> J
H --> M
I --> M
J --> N
K --> G
K --> D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
核心技术栈
层级 | 技术组件 | 版本要求 | 用途 |
---|---|---|---|
前端界面层 | PyQt5 | >=5.15.0 | GUI框架基础 |
QFluentWidgets | >=1.1.0 | Microsoft Fluent Design组件 | |
业务逻辑层 | Python | 3.7+ | 核心开发语言 |
pandas | >=1.5.0 | 数据处理和分析 | |
requests | >=2.28.0 | HTTP网络请求 | |
数据存储层 | openpyxl | >=3.0.0 | Excel文件操作 |
本地文件系统 | - | 图片和日志存储 | |
图像处理层 | Pillow | >=9.0.0 | 图像处理和格式转换 |
监控系统层 | watchdog | >=2.1.0 | 文件系统监控 |
打包部署层 | PyInstaller | - | 应用程序打包 |
🎯 设计模式
1. MVC模式变体
Model (数据模型层)
核心文件: malatang_processor.py
python
class MalatangProcessor:
"""主处理类 - Model层核心"""
def __init__(self):
self.logger = Logger.setup_logger()
self.data_extractor = DataExtractor(self.logger)
self.excel_manager = ExcelManager(self.logger)
self.image_downloader = ImageDownloader(self.logger)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
职责:
- 数据解析和提取
- 业务逻辑处理
- 文件操作管理
- 错误处理和日志
View (视图层)
核心文件: gui_fluent.py
python
class MalatangFluentGUI(FluentWindow):
"""Fluent Design主界面 - View层"""
def __init__(self):
super().__init__()
self.setWindowTitle("美团店铺数据处理工具")
self.setFixedSize(1400, 1244)
self.init_ui()
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
职责:
- 用户界面展示
- 用户交互处理
- 状态信息显示
- 主题和样式管理
Controller (控制器层)
核心文件: gui_processor.py
python
class GUIProcessor:
"""GUI专用处理器 - Controller层"""
def __init__(self, log_callback=None, progress_callback=None):
self.log_callback = log_callback
self.progress_callback = progress_callback
1
2
3
4
5
6
2
3
4
5
6
职责:
- 协调View和Model
- 处理用户输入
- 管理业务流程
- 提供回调接口
2. 观察者模式
文件监控系统
python
class QFileSystemWatcher:
"""文件系统监控 - 观察者模式"""
def fileChanged(self, file_path):
# 文件变化时通知所有观察者
self.notify_observers(file_path)
1
2
3
4
5
6
2
3
4
5
6
实现特点:
- 实时监控文件变化
- 自动触发处理流程
- 解耦监控和处理逻辑
信号槽机制
python
class ProcessorThread(QThread):
"""后台处理线程 - 信号槽模式"""
log_signal = pyqtSignal(str, str) # 日志信号
progress_signal = pyqtSignal(int) # 进度信号
finished_signal = pyqtSignal(dict) # 完成信号
1
2
3
4
5
6
2
3
4
5
6
3. 策略模式
多界面版本支持
python
# 不同的界面策略
gui_strategies = {
'fluent': 'gui_fluent.py', # Fluent Design界面
'enhanced': 'gui_enhanced.py', # 增强版界面
'basic': 'gui_main.py' # 基础界面
}
1
2
3
4
5
6
2
3
4
5
6
图片处理策略
python
class ImageProcessor:
"""图片处理策略"""
def process_image(self, strategy='jpg_conversion'):
if strategy == 'jpg_conversion':
return self.convert_to_jpg()
elif strategy == 'keep_original':
return self.keep_original_format()
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
4. 工厂模式
组件创建工厂
python
class ComponentFactory:
"""组件创建工厂"""
@staticmethod
def create_processor(processor_type='gui'):
if processor_type == 'gui':
return GUIProcessor()
elif processor_type == 'cli':
return CLIProcessor()
else:
return MalatangProcessor()
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
🧵 多线程架构
线程模型
mermaid
sequenceDiagram
participant U as 用户界面
participant PT as ProcessorThread
participant GP as GUIProcessor
participant FW as FileWatcher
participant FS as 文件系统
U->>PT: 启动处理线程
PT->>GP: 创建GUI处理器
U->>FW: 启用文件监控
loop 数据处理
PT->>GP: 解析JSON文件
GP-->>U: 发送日志信号
PT->>GP: 提取商品信息
GP-->>U: 发送进度信号
PT->>GP: 保存Excel数据
PT->>GP: 下载图片
GP-->>U: 发送完成信号
end
loop 文件监控
FW->>FS: 监控文件变化
FS-->>FW: 文件变化事件
FW->>U: 触发文件变化信号
U->>PT: 重新启动处理
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
线程安全机制
1. 信号槽通信
python
# 线程安全的信号槽通信
self.processor_thread.log_signal.connect(self.add_log)
self.processor_thread.progress_signal.connect(self.progress_bar.setValue)
self.processor_thread.finished_signal.connect(self.on_processing_finished)
1
2
3
4
2
3
4
2. 线程同步
python
class ProcessorThread(QThread):
def __init__(self):
super().__init__()
self.should_stop = False # 线程停止标志
self.mutex = QMutex() # 互斥锁
def stop(self):
with QMutexLocker(self.mutex):
self.should_stop = True
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
3. 资源管理
python
def cleanup_resources(self):
"""清理线程资源"""
if self.processor_thread and self.processor_thread.isRunning():
self.processor_thread.quit()
self.processor_thread.wait()
1
2
3
4
5
2
3
4
5
📊 数据流架构
数据处理流程
mermaid
flowchart TD
A[JSON数据文件] --> B[数据解析器]
B --> C[商品信息提取]
C --> D[数据验证清洗]
D --> E[Excel数据管理]
E --> F[图片下载处理]
F --> G[格式转换]
G --> H[文件保存]
I[配置文件] --> B
I --> E
I --> F
J[日志系统] --> B
J --> C
J --> D
J --> E
J --> F
J --> G
J --> H
K[错误处理] --> B
K --> C
K --> D
K --> E
K --> F
K --> G
K --> H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
数据模型设计
商品数据模型
python
@dataclass
class Product:
"""商品数据模型"""
name: str # 商品名称
price: float # 原价(元)
discount_price: float # 折扣价(元)
month_sale: int # 月销量
image_url: str # 图片链接
image_filename: str # 图片文件名
update_time: datetime # 更新时间
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Excel数据结构
python
EXCEL_COLUMNS = [
'商品名称', # 主键,用于去重
'原价', # 数值类型,保留2位小数
'折扣价', # 数值类型,保留2位小数
'月售数量', # 整数类型
'图片链接', # 文本类型,URL格式
'图片文件名', # 文本类型,本地文件名
'更新时间' # 日期时间类型
]
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
🔧 组件架构
核心组件详解
1. 数据提取组件 (DataExtractor)
python
class DataExtractor:
"""数据提取组件"""
def __init__(self, logger):
self.logger = logger
def parse_json_file(self, file_path: str) -> Dict:
"""解析JSON文件"""
def extract_products(self, data: Dict) -> List[Dict]:
"""提取商品信息"""
def _extract_single_product(self, item: Dict) -> Optional[Dict]:
"""提取单个商品信息"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
职责:
- JSON文件解析
- 数据结构验证
- 商品信息提取
- 异常处理
2. Excel管理组件 (ExcelManager)
python
class ExcelManager:
"""Excel管理组件"""
def load_existing_data(self, file_path: str) -> pd.DataFrame:
"""加载现有Excel数据"""
def save_products_to_excel(self, products: List[Dict], file_path: str):
"""保存商品数据到Excel"""
def _prepare_dataframe(self, products: List[Dict]) -> pd.DataFrame:
"""准备DataFrame数据"""
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
职责:
- Excel文件读写
- 数据格式转换
- 去重逻辑处理
- 追加模式支持
3. 图片下载组件 (ImageDownloader)
python
class ImageDownloader:
"""图片下载组件"""
def download_images(self, products: List[Dict], images_dir: str):
"""批量下载图片"""
def _download_single_image(self, url: str, filename: str) -> bool:
"""下载单个图片"""
def _convert_to_jpg(self, image_path: str) -> bool:
"""转换图片格式为JPG"""
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
职责:
- 图片批量下载
- 格式转换处理
- 文件命名管理
- 下载状态跟踪
组件间通信
依赖注入
python
class MalatangProcessor:
def __init__(self):
# 依赖注入,便于测试和扩展
self.logger = Logger.setup_logger()
self.data_extractor = DataExtractor(self.logger)
self.excel_manager = ExcelManager(self.logger)
self.image_downloader = ImageDownloader(self.logger)
1
2
3
4
5
6
7
2
3
4
5
6
7
接口标准化
python
class ProcessorInterface:
"""处理器接口"""
def process_file(self, input_file: str, output_excel: str, images_dir: str):
"""标准处理接口"""
raise NotImplementedError
1
2
3
4
5
6
2
3
4
5
6
🛡️ 错误处理架构
异常处理层次
mermaid
graph TD
A[用户操作] --> B[界面层异常处理]
B --> C[控制器层异常处理]
C --> D[业务逻辑层异常处理]
D --> E[组件层异常处理]
B --> F[用户友好提示]
C --> G[日志记录]
D --> H[业务回滚]
E --> I[资源清理]
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
异常类型定义
python
class MalatangProcessorError(Exception):
"""基础异常类"""
pass
class JSONParseError(MalatangProcessorError):
"""JSON解析异常"""
pass
class ImageDownloadError(MalatangProcessorError):
"""图片下载异常"""
pass
class ExcelOperationError(MalatangProcessorError):
"""Excel操作异常"""
pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
错误恢复机制
python
def robust_process_with_retry(self, operation, max_retries=3):
"""带重试的健壮处理"""
for attempt in range(max_retries):
try:
return operation()
except Exception as e:
if attempt == max_retries - 1:
raise
self.logger.warning(f"操作失败,正在重试 ({attempt + 1}/{max_retries}): {e}")
time.sleep(2 ** attempt) # 指数退避
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
📈 性能优化架构
内存管理
- 流式处理: 大文件分块读取
- 对象池: 重用频繁创建的对象
- 垃圾回收: 及时释放不用的资源
网络优化
- 连接池: 复用HTTP连接
- 并发下载: 多线程图片下载
- 智能重试: 指数退避重试机制
界面优化
- 异步处理: 后台线程处理数据
- 进度反馈: 实时更新处理进度
- 响应式设计: 界面始终保持响应
架构优势
- 模块化: 各组件职责清晰,易于维护
- 可扩展: 支持新功能和新界面的添加
- 健壮性: 完善的错误处理和恢复机制
- 性能: 多线程和优化策略确保高效处理
注意事项
- 修改核心架构时需要充分测试
- 新增组件应遵循现有的设计模式
- 保持接口的向后兼容性