-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_app.py
More file actions
314 lines (261 loc) · 8.63 KB
/
web_app.py
File metadata and controls
314 lines (261 loc) · 8.63 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""
Web应用 - Flask服务器
提供美观的Web界面查看统计结果
"""
import os
import logging
from datetime import datetime, timedelta
from flask import Flask, render_template, jsonify, request, send_file
import threading
from database import Database
from analyzer import DataAnalyzer
from monitor_service import ActivityMonitor
from config import WEB_HOST, WEB_PORT, DEBUG_MODE, STATIC_DIR, TEMPLATES_DIR, DATA_DIR
logger = logging.getLogger(__name__)
app = Flask(__name__,
static_folder=STATIC_DIR,
template_folder=TEMPLATES_DIR)
# 全局变量
monitor = None
analyzer = DataAnalyzer()
db = Database()
@app.route('/')
def index():
"""首页"""
return render_template('index.html')
@app.route('/api/status')
def get_status():
"""获取当前监控状态"""
if monitor:
status = monitor.get_current_status()
return jsonify({
'success': True,
'data': status
})
else:
return jsonify({
'success': False,
'message': '监控服务未启动'
})
@app.route('/api/today')
def get_today():
"""获取今日数据"""
try:
summary = analyzer.get_today_summary()
return jsonify({
'success': True,
'data': summary
})
except Exception as e:
logger.error(f"获取今日数据失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/week')
def get_week():
"""获取周报"""
try:
report = analyzer.get_week_report()
return jsonify({
'success': True,
'data': report
})
except Exception as e:
logger.error(f"获取周报失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/month')
def get_month():
"""获取月报"""
try:
year = request.args.get('year', type=int)
month = request.args.get('month', type=int)
report = analyzer.get_month_report(year, month)
return jsonify({
'success': True,
'data': report
})
except Exception as e:
logger.error(f"获取月报失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/custom')
def get_custom():
"""获取自定义时间段报表"""
try:
start_str = request.args.get('start')
end_str = request.args.get('end')
start_date = datetime.strptime(start_str, '%Y-%m-%d').date()
end_date = datetime.strptime(end_str, '%Y-%m-%d').date()
report = analyzer.get_custom_report(start_date, end_date)
return jsonify({
'success': True,
'data': report
})
except Exception as e:
logger.error(f"获取自定义报表失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/chart/busy_curve')
def get_busy_curve():
"""获取忙碌度曲线图"""
try:
date_str = request.args.get('date')
if date_str:
date = datetime.strptime(date_str, '%Y-%m-%d').date()
else:
date = datetime.now().date()
chart_path = analyzer.generate_busy_curve(date)
if chart_path and os.path.exists(chart_path):
return jsonify({
'success': True,
'data': {
'url': f'/static/{os.path.basename(chart_path)}'
}
})
else:
return jsonify({
'success': False,
'message': '生成图表失败或无数据'
})
except Exception as e:
logger.error(f"生成忙碌度曲线图失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/chart/heatmap')
def get_heatmap():
"""获取热力图"""
try:
start_str = request.args.get('start')
end_str = request.args.get('end')
if start_str and end_str:
start_date = datetime.strptime(start_str, '%Y-%m-%d').date()
end_date = datetime.strptime(end_str, '%Y-%m-%d').date()
else:
end_date = datetime.now().date()
start_date = end_date - timedelta(days=30)
chart_path = analyzer.generate_heatmap(start_date, end_date)
if chart_path and os.path.exists(chart_path):
return jsonify({
'success': True,
'data': {
'url': f'/static/{os.path.basename(chart_path)}'
}
})
else:
return jsonify({
'success': False,
'message': '生成图表失败或无数据'
})
except Exception as e:
logger.error(f"生成热力图失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/chart/trend')
def get_trend():
"""获取趋势图"""
try:
start_str = request.args.get('start')
end_str = request.args.get('end')
if start_str and end_str:
start_date = datetime.strptime(start_str, '%Y-%m-%d').date()
end_date = datetime.strptime(end_str, '%Y-%m-%d').date()
else:
end_date = datetime.now().date()
start_date = end_date - timedelta(days=7)
chart_path = analyzer.generate_trend_chart(start_date, end_date)
if chart_path and os.path.exists(chart_path):
return jsonify({
'success': True,
'data': {
'url': f'/static/{os.path.basename(chart_path)}'
}
})
else:
return jsonify({
'success': False,
'message': '生成图表失败或无数据'
})
except Exception as e:
logger.error(f"生成趋势图失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/export/csv')
def export_csv():
"""导出CSV"""
try:
start_str = request.args.get('start')
end_str = request.args.get('end')
start_date = datetime.strptime(start_str, '%Y-%m-%d').date()
end_date = datetime.strptime(end_str, '%Y-%m-%d').date()
filename = f'activity_report_{start_date}_{end_date}.csv'
output_path = os.path.join(DATA_DIR, filename)
success = analyzer.export_to_csv(start_date, end_date, output_path)
if success:
return send_file(output_path,
as_attachment=True,
download_name=filename)
else:
return jsonify({
'success': False,
'message': '导出失败'
})
except Exception as e:
logger.error(f"导出CSV失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@app.route('/api/export/excel')
def export_excel():
"""导出Excel"""
try:
start_str = request.args.get('start')
end_str = request.args.get('end')
start_date = datetime.strptime(start_str, '%Y-%m-%d').date()
end_date = datetime.strptime(end_str, '%Y-%m-%d').date()
filename = f'activity_report_{start_date}_{end_date}.xlsx'
output_path = os.path.join(DATA_DIR, filename)
success = analyzer.export_to_excel(start_date, end_date, output_path)
if success:
return send_file(output_path,
as_attachment=True,
download_name=filename)
else:
return jsonify({
'success': False,
'message': '导出失败'
})
except Exception as e:
logger.error(f"导出Excel失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
def start_web_server(monitor_instance):
"""启动Web服务器"""
global monitor
monitor = monitor_instance
logger.info(f"Web服务器启动于 http://{WEB_HOST}:{WEB_PORT}")
app.run(host=WEB_HOST, port=WEB_PORT, debug=DEBUG_MODE, use_reloader=False)
def run_in_thread(monitor_instance):
"""在独立线程中运行Web服务器"""
thread = threading.Thread(target=start_web_server, args=(monitor_instance,), daemon=True)
thread.start()
return thread
if __name__ == '__main__':
# 仅用于测试
start_web_server(None)