mdbq 4.0.80__py3-none-any.whl → 4.0.81__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mdbq/route/example.py ADDED
@@ -0,0 +1,378 @@
1
+ """
2
+ 路由监控系统集成示例
3
+ 展示如何在现有的Flask应用中集成路由监控功能
4
+
5
+ 重点:批量装饰器应用 - 无需手动为每个函数添加装饰器!
6
+
7
+ 使用方法:
8
+ 1. 导入监控模块
9
+ 2. 定义需要监控的路由列表
10
+ 3. 批量应用装饰器
11
+ 4. 可选择性地添加全局监控
12
+
13
+ """
14
+
15
+ # ========================================
16
+ # 方法1:批量装饰器应用(强烈推荐)
17
+ # ========================================
18
+
19
+ from monitor import monitor_request, get_request_id, get_statistics_summary
20
+ from routes import register_routes
21
+
22
+ # 在 dpflask.py 文件末尾添加以下代码:
23
+
24
+ # 第一步:定义需要监控的路由函数名列表
25
+ MONITORED_ROUTES = [
26
+ # DeepSeek相关接口
27
+ 'deepseek_request', # 主要接口
28
+ 'deepseek_public_key', # 获取公钥接口
29
+ 'deepseek_update', # 更新日志接口
30
+ 'deepseek_feedback', # 客户端反馈接口
31
+ 'deepseek_chat_history', # 加载历史记录接口
32
+ 'deepseek_client_id_save_user_info', # 存储client id
33
+ 'deepseek_client_id_auth_user_info', # 校检client id
34
+
35
+ # 生意参谋相关接口
36
+ 'sycm_access_control_info', # 访问控制信息
37
+ 'sycm_load_userinfo', # 用户信息加载
38
+ 'sycm_list_database', # 数据库列表
39
+ 'sycm_list_tables', # 数据表列表
40
+ 'sycm_view_table', # 查看表数据
41
+ ]
42
+
43
+ # 第二步:批量应用监控装饰器的函数
44
+ def apply_monitor_to_routes(app_globals, route_names):
45
+ """
46
+ 为指定的路由函数批量添加监控装饰器
47
+
48
+ 优势:
49
+ - 无需手动修改每个函数
50
+ - 统一管理监控配置
51
+ - 避免遗漏或重复
52
+ - 便于维护
53
+ """
54
+ applied_count = 0
55
+ skipped_count = 0
56
+
57
+ print("🚀 开始批量应用监控装饰器...")
58
+
59
+ for route_name in route_names:
60
+ if route_name in app_globals and callable(app_globals[route_name]):
61
+ # 检查是否已经添加过监控装饰器
62
+ if not hasattr(app_globals[route_name], '_is_monitored'):
63
+ # 应用监控装饰器
64
+ app_globals[route_name] = monitor_request(app_globals[route_name])
65
+ app_globals[route_name]._is_monitored = True
66
+ applied_count += 1
67
+ print(f" ✅ 已为 {route_name} 添加监控")
68
+ else:
69
+ skipped_count += 1
70
+ print(f" ⚠️ {route_name} 已经有监控装饰器,跳过")
71
+ else:
72
+ print(f" ❌ 未找到函数: {route_name}")
73
+
74
+ print(f"📊 批量装饰器应用完成:")
75
+ print(f" - 成功添加: {applied_count} 个")
76
+ print(f" - 已存在跳过: {skipped_count} 个")
77
+ print(f" - 总计处理: {len(route_names)} 个")
78
+
79
+ # 第三步:执行批量应用(在 dpflask.py 文件最后添加)
80
+ """
81
+ # 批量应用监控装饰器
82
+ apply_monitor_to_routes(globals(), MONITORED_ROUTES)
83
+
84
+ # 注册管理界面路由
85
+ register_routes(app)
86
+
87
+ print("🎯 路由监控系统初始化完成!")
88
+ """
89
+
90
+ # ========================================
91
+ # 方法2:按模式自动应用(更智能)
92
+ # ========================================
93
+
94
+ def auto_apply_monitor_by_pattern(app_globals, pattern_prefixes=None, exclude_patterns=None):
95
+ """
96
+ 根据函数名模式自动添加监控装饰器
97
+
98
+ Args:
99
+ pattern_prefixes: 匹配的函数名前缀,如 ['deepseek_', 'sycm_']
100
+ exclude_patterns: 排除的模式,如 ['_test', '_internal']
101
+ """
102
+ if pattern_prefixes is None:
103
+ pattern_prefixes = ['deepseek_', 'sycm_', 'api_']
104
+
105
+ if exclude_patterns is None:
106
+ exclude_patterns = ['_test', '_internal', '_helper', '_debug']
107
+
108
+ applied_count = 0
109
+
110
+ print("🔍 开始自动扫描并应用监控装饰器...")
111
+
112
+ for name, obj in app_globals.items():
113
+ # 检查是否为函数且符合命名模式
114
+ if callable(obj) and any(name.startswith(prefix) for prefix in pattern_prefixes):
115
+ # 检查是否需要排除
116
+ if any(exclude in name for exclude in exclude_patterns):
117
+ print(f" 🚫 跳过排除的函数: {name}")
118
+ continue
119
+
120
+ # 检查是否已经有监控装饰器
121
+ if not hasattr(obj, '_is_monitored'):
122
+ app_globals[name] = monitor_request(obj)
123
+ app_globals[name]._is_monitored = True
124
+ applied_count += 1
125
+ print(f" ✅ 自动为 {name} 添加监控")
126
+
127
+ print(f"🎯 自动扫描完成,为 {applied_count} 个路由添加了监控")
128
+
129
+ # 使用自动模式的示例:
130
+ """
131
+ # 自动为所有以 deepseek_ 和 sycm_ 开头的函数添加监控
132
+ auto_apply_monitor_by_pattern(globals(),
133
+ pattern_prefixes=['deepseek_', 'sycm_'],
134
+ exclude_patterns=['_test', '_internal', '_debug']
135
+ )
136
+ """
137
+
138
+ # ========================================
139
+ # 方法3:环境感知的监控配置(生产级)
140
+ # ========================================
141
+
142
+ import os
143
+
144
+ class MonitorConfig:
145
+ """监控配置管理类 - 根据环境应用不同的监控策略"""
146
+
147
+ # 核心业务接口(所有环境都监控)
148
+ CRITICAL_ROUTES = [
149
+ 'deepseek_request',
150
+ 'sycm_list_database',
151
+ 'sycm_view_table',
152
+ ]
153
+
154
+ # 重要接口(生产和测试环境监控)
155
+ IMPORTANT_ROUTES = [
156
+ 'deepseek_public_key',
157
+ 'deepseek_chat_history',
158
+ 'sycm_load_userinfo',
159
+ 'sycm_list_tables',
160
+ ]
161
+
162
+ # 辅助接口(仅生产环境监控)
163
+ AUXILIARY_ROUTES = [
164
+ 'deepseek_update',
165
+ 'deepseek_feedback',
166
+ 'sycm_access_control_info',
167
+ 'deepseek_client_id_save_user_info',
168
+ 'deepseek_client_id_auth_user_info',
169
+ ]
170
+
171
+ @classmethod
172
+ def apply_monitoring(cls, app_globals, environment=None):
173
+ """
174
+ 根据环境应用相应的监控策略
175
+
176
+ Args:
177
+ environment: 'production', 'staging', 'development' 或 None(自动检测)
178
+ """
179
+ if environment is None:
180
+ environment = os.getenv('FLASK_ENV', 'development')
181
+
182
+ routes_to_monitor = []
183
+
184
+ # 根据环境确定监控范围
185
+ if environment == 'production':
186
+ routes_to_monitor.extend(cls.CRITICAL_ROUTES)
187
+ routes_to_monitor.extend(cls.IMPORTANT_ROUTES)
188
+ routes_to_monitor.extend(cls.AUXILIARY_ROUTES)
189
+ print("🔥 生产环境:启用完整监控")
190
+
191
+ elif environment == 'staging':
192
+ routes_to_monitor.extend(cls.CRITICAL_ROUTES)
193
+ routes_to_monitor.extend(cls.IMPORTANT_ROUTES)
194
+ print("🧪 测试环境:启用重要接口监控")
195
+
196
+ else: # development
197
+ routes_to_monitor.extend(cls.CRITICAL_ROUTES)
198
+ print("🔧 开发环境:仅监控核心接口")
199
+
200
+ # 应用监控
201
+ apply_monitor_to_routes(app_globals, routes_to_monitor)
202
+ print(f"📊 {environment} 环境监控配置已应用")
203
+
204
+ # 环境感知监控的使用示例:
205
+ """
206
+ # 在 dpflask.py 文件末尾添加:
207
+
208
+ # 根据环境自动应用监控配置
209
+ MonitorConfig.apply_monitoring(globals())
210
+
211
+ # 手动指定环境
212
+ # MonitorConfig.apply_monitoring(globals(), 'production')
213
+
214
+ # 注册管理界面
215
+ register_routes(app)
216
+ """
217
+
218
+ # ========================================
219
+ # 方法4:带条件的智能监控(高级用法)
220
+ # ========================================
221
+
222
+ def conditional_monitor_routes(app_globals, route_conditions):
223
+ """
224
+ 根据条件应用监控装饰器
225
+
226
+ Args:
227
+ route_conditions: 字典,格式为 {函数名: 条件函数}
228
+ """
229
+ applied_count = 0
230
+
231
+ for route_name, condition_func in route_conditions.items():
232
+ if route_name in app_globals and callable(app_globals[route_name]):
233
+ if condition_func():
234
+ if not hasattr(app_globals[route_name], '_is_monitored'):
235
+ app_globals[route_name] = monitor_request(app_globals[route_name])
236
+ app_globals[route_name]._is_monitored = True
237
+ applied_count += 1
238
+ print(f" ✅ 条件满足,为 {route_name} 添加监控")
239
+ else:
240
+ print(f" ⚠️ {route_name} 已有监控装饰器")
241
+ else:
242
+ print(f" 🚫 条件不满足,跳过 {route_name}")
243
+
244
+ print(f"🎯 条件监控应用完成,处理了 {applied_count} 个路由")
245
+
246
+ # 条件监控示例:
247
+ """
248
+ # 定义条件函数
249
+ def is_production():
250
+ return os.getenv('FLASK_ENV') == 'production'
251
+
252
+ def is_debug_enabled():
253
+ return os.getenv('DEBUG', '').lower() == 'true'
254
+
255
+ # 定义条件监控规则
256
+ CONDITIONAL_ROUTES = {
257
+ 'deepseek_request': lambda: True, # 总是监控
258
+ 'deepseek_update': is_production, # 仅生产环境监控
259
+ 'sycm_view_table': is_production, # 仅生产环境监控
260
+ 'debug_endpoint': is_debug_enabled, # 仅调试模式监控
261
+ }
262
+
263
+ # 应用条件监控
264
+ conditional_monitor_routes(globals(), CONDITIONAL_ROUTES)
265
+ """
266
+
267
+ # ========================================
268
+ # 完整的集成示例代码
269
+ # ========================================
270
+
271
+ COMPLETE_INTEGRATION_EXAMPLE = '''
272
+ # ================================================
273
+ # 在 dpflask.py 文件末尾添加以下完整代码
274
+ # ================================================
275
+
276
+ # 1. 导入监控模块
277
+ from route.monitor import monitor_request, get_request_id, get_statistics_summary
278
+ from route.routes import register_routes
279
+ import os
280
+
281
+ # 2. 批量装饰器应用函数
282
+ def apply_monitor_to_routes(app_globals, route_names):
283
+ """批量为路由函数添加监控装饰器"""
284
+ applied_count = 0
285
+ for route_name in route_names:
286
+ if route_name in app_globals and callable(app_globals[route_name]):
287
+ if not hasattr(app_globals[route_name], '_is_monitored'):
288
+ app_globals[route_name] = monitor_request(app_globals[route_name])
289
+ app_globals[route_name]._is_monitored = True
290
+ applied_count += 1
291
+ print(f"✅ 已为 {route_name} 添加监控")
292
+ print(f"🎯 总计为 {applied_count} 个路由添加了监控")
293
+
294
+ # 3. 定义需要监控的路由列表
295
+ MONITORED_ROUTES = [
296
+ 'deepseek_request',
297
+ 'deepseek_public_key',
298
+ 'deepseek_chat_history',
299
+ 'sycm_list_database',
300
+ 'sycm_view_table',
301
+ # 根据需要添加更多路由
302
+ ]
303
+
304
+ # 4. 应用监控
305
+ print("🚀 正在初始化路由监控系统...")
306
+ apply_monitor_to_routes(globals(), MONITORED_ROUTES)
307
+
308
+ # 5. 注册管理界面
309
+ register_routes(app)
310
+
311
+ # 6. 完成提示
312
+ current_env = os.getenv('FLASK_ENV', 'development')
313
+ print(f"✨ 路由监控系统初始化完成!")
314
+ print(f"🔧 当前环境: {current_env}")
315
+ print(f"📊 管理界面: http://localhost:5000/admin/monitor/dashboard")
316
+
317
+ # 可选:添加一些简单的管理接口
318
+ @app.route('/admin/monitor/stats', methods=['GET'])
319
+ def get_monitor_stats():
320
+ """获取监控统计信息"""
321
+ try:
322
+ days = request.args.get('days', 7, type=int)
323
+ stats = get_statistics_summary(days)
324
+ return jsonify({
325
+ 'code': 0,
326
+ 'status': 'success',
327
+ 'data': stats
328
+ })
329
+ except Exception as e:
330
+ return jsonify({
331
+ 'code': 500,
332
+ 'status': 'error',
333
+ 'message': str(e)
334
+ }), 500
335
+ '''
336
+
337
+ # ========================================
338
+ # 总结说明
339
+ # ========================================
340
+
341
+ print("""
342
+ 🎯 批量装饰器的核心优势:
343
+
344
+ 1. ✅ 无需手动修改每个函数定义
345
+ - 原始函数保持不变
346
+ - 所有装饰器在一个地方统一管理
347
+
348
+ 2. ✅ 灵活的监控策略
349
+ - 可以根据环境启用不同的监控范围
350
+ - 支持条件性监控
351
+ - 便于测试和调试
352
+
353
+ 3. ✅ 维护性强
354
+ - 新增监控只需在列表中添加函数名
355
+ - 移除监控只需从列表中删除
356
+ - 避免在代码中到处添加装饰器
357
+
358
+ 4. ✅ 性能优化
359
+ - 避免重复装饰
360
+ - 自动检测已有装饰器
361
+ - 支持条件性启用
362
+
363
+ 📋 推荐使用方式:
364
+ - 开发阶段:使用方法1(明确的函数名列表)
365
+ - 生产环境:使用方法3(环境感知配置)
366
+ - 大型项目:结合多种方法,分模块管理
367
+
368
+ 🔧 集成步骤:
369
+ 1. 复制 COMPLETE_INTEGRATION_EXAMPLE 中的代码
370
+ 2. 添加到 dpflask.py 文件末尾
371
+ 3. 根据需要调整 MONITORED_ROUTES 列表
372
+ 4. 重启应用即可生效
373
+
374
+ 这样就实现了批量添加监控装饰器,无需手动修改每个函数!
375
+ """)
376
+
377
+ if __name__ == "__main__":
378
+ print(COMPLETE_INTEGRATION_EXAMPLE)