Skip to content

Commit 00cd7ff

Browse files
committed
Fix app.py 3
1 parent 356da9f commit 00cd7ff

1 file changed

Lines changed: 35 additions & 38 deletions

File tree

backend/api/app.py

Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,40 @@
1212
JSON_FILE = os.path.join(STATS_DIR, "fast_statistics.json")
1313
IMAGE_PATTERN = os.path.join(STATS_DIR, "stats{}.png")
1414

15+
def get_time_periods():
16+
now = datetime.now()
17+
return {
18+
"day": now - timedelta(days=1),
19+
"month": now - timedelta(days=30),
20+
"all_time": datetime.min
21+
}
22+
23+
def update_stats_file(app):
24+
"""Background task to update statistics JSON file"""
25+
while True:
26+
try:
27+
with app.app_context():
28+
periods = get_time_periods()
29+
period_stats = {}
30+
31+
for period, start_date in periods.items():
32+
period_stats[period] = {
33+
"total": app.data_collection.count_documents({"timestamp": {"$gte": start_date}}),
34+
"unique": len(app.data_collection.distinct("fingerprint", {"timestamp": {"$gte": start_date}}))
35+
}
36+
37+
stats_data = {"periodStats": period_stats}
38+
39+
with open(JSON_FILE, 'w') as f:
40+
json.dump(stats_data, f)
41+
42+
generate_statistics_images(stats_data, IMAGE_PATTERN)
43+
44+
except Exception as e:
45+
app.logger.error(f"Error updating stats: {str(e)}")
46+
47+
time.sleep(30)
48+
1549
def create_app():
1650
app = Flask(__name__)
1751

@@ -24,51 +58,14 @@ def create_app():
2458
os.makedirs(STATS_DIR, exist_ok=True)
2559

2660
# Start background thread
27-
def run_update_thread():
28-
with app.app_context():
29-
update_stats_file()
30-
31-
thread = threading.Thread(target=run_update_thread)
61+
thread = threading.Thread(target=update_stats_file, args=(app,))
3262
thread.daemon = True
3363
thread.start()
3464

3565
return app
3666

3767
app = create_app()
3868

39-
def get_time_periods():
40-
now = datetime.now()
41-
return {
42-
"day": now - timedelta(days=1),
43-
"month": now - timedelta(days=30),
44-
"all_time": datetime.min
45-
}
46-
47-
def update_stats_file():
48-
"""Background task to update statistics JSON file"""
49-
while True:
50-
try:
51-
periods = get_time_periods()
52-
period_stats = {}
53-
54-
for period, start_date in periods.items():
55-
period_stats[period] = {
56-
"total": app.data_collection.count_documents({"timestamp": {"$gte": start_date}}),
57-
"unique": len(app.data_collection.distinct("fingerprint", {"timestamp": {"$gte": start_date}}))
58-
}
59-
60-
stats_data = {"periodStats": period_stats}
61-
62-
with open(JSON_FILE, 'w') as f:
63-
json.dump(stats_data, f)
64-
65-
generate_statistics_images(stats_data, IMAGE_PATTERN)
66-
67-
except Exception as e:
68-
app.logger.error(f"Error updating stats: {str(e)}")
69-
70-
time.sleep(30)
71-
7269
@app.route('/post', methods=['POST'])
7370
def log_data():
7471
data = request.get_json()

0 commit comments

Comments
 (0)