-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
165 lines (134 loc) · 5.5 KB
/
app.py
File metadata and controls
165 lines (134 loc) · 5.5 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
from flask import Flask, render_template, send_file
import datetime
from zoneinfo import ZoneInfo
import time
import io
import hashlib
from concurrent.futures import ThreadPoolExecutor
# Import from our new data layer
from data_services import get_weather, get_calendar_info, get_hacker_news, generate_sparkline
from config import Config
executor = ThreadPoolExecutor(max_workers=20)
app = Flask(__name__)
# Simple in-memory cache for the /render endpoint
# Format: {"data": bytes, "timestamp": float}
_render_cache = {"data": None, "timestamp": 0}
@app.route('/health')
def health():
print("Health check hit")
return "OK"
@app.route('/dashboard')
def dashboard():
# Submit Data Fetch Tasks in Parallel
future_weather = executor.submit(get_weather)
future_calendar = executor.submit(get_calendar_info)
future_news = executor.submit(get_hacker_news)
# Finance Tasks
tickers = Config.get_finance_tickers()
future_finance = [(t, executor.submit(generate_sparkline, t['symbol'])) for t in tickers]
# Gather Results
try:
weather = future_weather.result(timeout=15)
except Exception as e:
print(f"Weather Timeout: {e}")
weather = {"current": {"temp": "--"}, "forecast": [], "tomorrow": {}}
try:
calendar = future_calendar.result(timeout=5)
except:
calendar = {"date_str": "--", "weekday": "--", "lunar": "--"}
try:
news = future_news.result(timeout=15)
except:
news = []
finance_data = []
for t, future in future_finance:
try:
chart, price, change = future.result(timeout=15)
except:
chart, price, change = None, "--", 0
# Formatting Price
if price == "--":
p_str = "--"
elif "BTC" in t['name']:
p_str = f"{price:,.0f}"
else:
try:
p_str = f"{price:.4f}"
except: p_str = str(price)
finance_data.append({
"name": t['name'],
"price": p_str,
"change": change,
"chart": chart
})
return render_template('dashboard.html',
weather=weather,
finance=finance_data,
calendar=calendar,
news=news,
updated_at=datetime.datetime.now(ZoneInfo(Config.TIMEZONE)).strftime("%H:%M"),
config=Config)
import os
import signal
# Global counter for consecutive rendering errors
_consecutive_render_failures = 0
MAX_RENDER_FAILURES = 5
@app.route('/render')
@app.route('/render.png')
def render_dashboard():
from renderer import render_dashboard_to_bytes
global _render_cache, _consecutive_render_failures
current_time = time.time()
def prepare_response(data, timestamp):
# Reset failure counter on success
global _consecutive_render_failures
_consecutive_render_failures = 0
response = send_file(
io.BytesIO(data),
mimetype='image/png',
as_attachment=False,
download_name='dashboard.png'
)
# Cloudflare loves extensions and explicit CDN cache headers
# s-maxage is for shared caches (like CF)
response.headers['Cache-Control'] = f'public, max-age={Config.CACHE_TTL_RENDER}, s-maxage={Config.CACHE_TTL_RENDER}'
# Last-Modified helps CF with validation
last_modified = datetime.datetime.fromtimestamp(timestamp, datetime.UTC)
response.headers['Last-Modified'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT')
# ETag for strong validation
etag = hashlib.md5(data).hexdigest()
response.set_etag(etag)
return response
# 1. Check if we have a valid cache
if _render_cache["data"] and (current_time - _render_cache["timestamp"] < Config.CACHE_TTL_RENDER):
print(f"Returning cached image (age: {int(current_time - _render_cache['timestamp'])}s)")
return prepare_response(_render_cache["data"], _render_cache["timestamp"])
# 2. If not cached, render it
port = Config.PORT
dashboard_url = f"http://127.0.0.1:{port}/dashboard"
try:
image_io = render_dashboard_to_bytes(dashboard_url)
# Read the io.BytesIO content to store it in cache
image_bytes = image_io.getvalue()
# Update Cache
_render_cache["data"] = image_bytes
_render_cache["timestamp"] = current_time
return prepare_response(image_bytes, current_time)
except Exception as e:
import traceback
traceback.print_exc()
_consecutive_render_failures += 1
print(f"Rendering failed. Failure count: {_consecutive_render_failures}/{MAX_RENDER_FAILURES}")
if _consecutive_render_failures >= MAX_RENDER_FAILURES:
print("CRITICAL: Too many consecutive rendering errors. Restarting container...")
# Send SIGTERM to PID 1 to trigger container restart
# Note: This works if the container is running as root (default)
try:
os.kill(1, signal.SIGTERM)
except PermissionError:
print("Could not kill PID 1 (Permission Denied). Killing self instead.")
os.kill(os.getpid(), signal.SIGTERM)
return f"Error rendering dashboard: {e}", 500
if __name__ == '__main__':
print("Starting app...")
app.run(debug=True, port=Config.PORT, host=Config.HOST)