From d34aa7f62040c811c475c731e936e6a80aac1360 Mon Sep 17 00:00:00 2001 From: Xevion Date: Fri, 19 Jun 2020 17:55:29 -0500 Subject: [PATCH] implement /api/changed route, new lastModified function --- trivia/api.py | 8 ++++++-- trivia/utils.py | 13 ++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/trivia/api.py b/trivia/api.py index bc87bab..7626669 100644 --- a/trivia/api.py +++ b/trivia/api.py @@ -3,9 +3,12 @@ api.py Handles backend routes assisting """ +import json + from flask import request from trivia import app +from trivia.utils import lastModified @app.route("/api/changed") @@ -18,8 +21,9 @@ def changed(): TODO: Remove this function once a proper 304 Not Modified implementation is found for client side. """ - - time = request.args.get('last') + from trivia.utils import lastChange + time = int(request.args.get('last') or lastModified()) + return json.dumps(lastChange < time) @app.route("/api/refresh") diff --git a/trivia/utils.py b/trivia/utils.py index df5da76..12f9392 100644 --- a/trivia/utils.py +++ b/trivia/utils.py @@ -12,12 +12,20 @@ from trivia import Team # Generate paths BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.join(BASE_DIR, 'data') +SCORES_FILE = os.path.join(DATA_DIR, 'scores.json') # Initialize global data/tracking vars lastChange: int = -1 teams: List[Team] = [] +def lastModified() -> float: + """ + returns epoch time of last modification to the scores file. + """ + return os.stat(SCORES_FILE).st_mtime + + def refreshScores() -> None: """ Refreshes scores data safely. @@ -26,8 +34,7 @@ def refreshScores() -> None: """ global lastChange - filepath = os.path.join(DATA_DIR, 'scores.json') - curChange = os.stat(filepath).st_mtime + curChange = lastModified() if lastChange < curChange: try: @@ -35,7 +42,7 @@ def refreshScores() -> None: lastChange = curChange print('Attempting to load and parse scores file.') - with open(filepath) as file: + with open(SCORES_FILE) as file: temp = json.load(file) # Place all values into Team object for jinja