added cache class for proper thread safety
This commit is contained in:
+14
-13
@@ -6,8 +6,10 @@ from src.parser import (
|
||||
get_last_n_days,
|
||||
get_stats,
|
||||
)
|
||||
from src.cache import Cache
|
||||
|
||||
app = Flask(__name__)
|
||||
sessions_cache = Cache()
|
||||
|
||||
REFETCH_MINUTES = os.environ.get("REFETCH_INTERVAL_MINUTES", "5")
|
||||
if not REFETCH_MINUTES.isdigit():
|
||||
@@ -17,7 +19,7 @@ REFETCH_SECONDS = int(REFETCH_MINUTES) * 60
|
||||
|
||||
# initial data fetch (required to work)
|
||||
try:
|
||||
sessions = get_this_semesters_sessions()
|
||||
sessions_cache.set(get_this_semesters_sessions())
|
||||
except Exception:
|
||||
print("Failed to fetch from calDAV server.")
|
||||
sys.exit(1)
|
||||
@@ -25,35 +27,34 @@ except Exception:
|
||||
# web ui
|
||||
@app.route("/")
|
||||
def index():
|
||||
current = list(sessions)
|
||||
labels = [s["subject"] for s in current]
|
||||
values = [s["minutes"] for s in current]
|
||||
return render_template("index.html", labels=labels, values=values, sessions=current)
|
||||
sessions = sessions_cache.get()
|
||||
labels = [s["subject"] for s in sessions]
|
||||
values = [s["minutes"] for s in sessions]
|
||||
return render_template("index.html", labels=labels, values=values, sessions=sessions)
|
||||
|
||||
# internal api
|
||||
@app.route("/api/dashboard")
|
||||
def api_dashboard():
|
||||
current = list(sessions)
|
||||
totals = calculate_totals(current)
|
||||
sessions = sessions_cache.get()
|
||||
totals = calculate_totals(sessions)
|
||||
return jsonify({
|
||||
"sessions": current,
|
||||
"sessions": sessions,
|
||||
"subjectTotals": totals,
|
||||
"dailyMinutes": get_last_n_days(50, current),
|
||||
"stats": get_stats(current, totals),
|
||||
"dailyMinutes": get_last_n_days(50, sessions),
|
||||
"stats": get_stats(sessions, totals),
|
||||
})
|
||||
|
||||
# external api
|
||||
@app.route("/api/sessions")
|
||||
def api_sessions():
|
||||
return jsonify(list(sessions))
|
||||
return jsonify(sessions_cache.get())
|
||||
|
||||
# background daemon
|
||||
def fetch_job():
|
||||
global sessions
|
||||
while True:
|
||||
time.sleep(REFETCH_SECONDS)
|
||||
try:
|
||||
sessions = get_this_semesters_sessions()
|
||||
sessions_cache.set(get_this_semesters_sessions())
|
||||
print("Successfully fetched data from calDAV")
|
||||
except Exception:
|
||||
print("Failed to refresh from calDAV server, keeping old data.")
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import threading
|
||||
|
||||
class Cache:
|
||||
def __init__(self):
|
||||
self._lock = threading.Lock()
|
||||
self._sessions = []
|
||||
|
||||
def get(self) -> list:
|
||||
with self._lock:
|
||||
return list(self._sessions)
|
||||
|
||||
def set(self, sessions: list):
|
||||
with self._lock:
|
||||
self._sessions = sessions
|
||||
Reference in New Issue
Block a user