fix timezones messing with epoch strptime conversion, re-standardized

This commit is contained in:
Xevion
2020-06-21 07:59:41 -05:00
parent 4fd1ecb1c4
commit 952f1c22a2
5 changed files with 14 additions and 9 deletions

10
cli.py
View File

@@ -15,7 +15,7 @@ from terminaltables import SingleTable
scores: List[dict] = [] scores: List[dict] = []
lastAttempt: float = -1 lastAttempt: float = -1
lastUpdate: datetime = None lastUpdate: float = -1
def refreshScores() -> bool: def refreshScores() -> bool:
@@ -30,7 +30,7 @@ def refreshScores() -> bool:
global lastUpdate, lastAttempt, scores global lastUpdate, lastAttempt, scores
# Send with If-Modified-Since header if this is not the first time # Send with If-Modified-Since header if this is not the first time
headers = {'If-Modified-Since': lastUpdate.strftime('%a, %d %b %Y %I:%M:%S %Z')} if lastUpdate else {} headers = {'If-Modified-Since': datetime.fromtimestamp(lastAttempt).strftime('%a, %d %b %Y %I:%M:%S')} if lastAttempt > 0 else {}
# Send request with headers # Send request with headers
try: try:
resp = requests.get('http://127.0.0.1:5000/api/scores/', headers=headers) resp = requests.get('http://127.0.0.1:5000/api/scores/', headers=headers)
@@ -44,7 +44,7 @@ def refreshScores() -> bool:
pass pass
else: else:
# Changes found, update! # Changes found, update!
lastUpdate = datetime.now(pytz.utc) lastUpdate = time.time()
scores = resp.json() scores = resp.json()
# Calculate totals, preliminary sort by total # Calculate totals, preliminary sort by total
@@ -80,7 +80,7 @@ def main(screen) -> None:
screen.redrawwin() screen.redrawwin()
while True: while True:
# Refresh scores every 10 seconds # Refresh scores every 10 seconds
if time.time() - lastAttempt > 1.5: if time.time() - lastAttempt > 0.5:
refreshScores() refreshScores()
# Get current terminal size and clear # Get current terminal size and clear
@@ -104,7 +104,7 @@ def main(screen) -> None:
# Terminal Size # Terminal Size
strpos = str((x, y)) strpos = str((x, y))
screen.addstr(y - 1, 1, strpos) screen.addstr(y - 1, 1, strpos)
screen.addstr(y - 1, 1 + len(strpos) + 1, f'({str(round(1.5 - (time.time() - lastAttempt), 3)).zfill(3)})') screen.addstr(y - 1, 1 + len(strpos) + 1, f'({str(round(0.5 - (time.time() - lastAttempt), 3)).zfill(3)})')
# Update curses screen # Update curses screen
screen.refresh() screen.refresh()

View File

@@ -6,6 +6,7 @@ Handles backend routes assisting
import json import json
import time import time
from datetime import datetime
from flask import request, make_response, current_app from flask import request, make_response, current_app
@@ -26,12 +27,12 @@ def scores():
try: try:
if request.headers['If-Modified-Since']: if request.headers['If-Modified-Since']:
# Acquire epoch time from header # Acquire epoch time from header
epoch = time.mktime(time.strptime(request.headers['If-Modified-Since'], "%a, %d %b %Y %I:%M:%S %Z")) epoch = time.mktime(time.strptime(request.headers['If-Modified-Since'], "%a, %d %b %Y %I:%M:%S"))
if epoch < lastChange: if epoch >= lastChange:
status_code = 304 status_code = 304
except KeyError: except KeyError:
pass # Header was not supplied. Ignore. pass # Header was not supplied. Ignore.
except ValueError: except ValueError:
current_app.logger.warning('If-Modified-Since Header could not be parsed.') # Header could not be parsed. current_app.logger.warning('If-Modified-Since Header could not be parsed.', exc_info=True) # Header could not be parsed.
return r, status_code return r, status_code

View File

@@ -22,6 +22,7 @@ class Config(object):
DEMO_ALTERATION_INTERVAL = 0 DEMO_ALTERATION_INTERVAL = 0
DEMO_MAX_SCORES = 0 DEMO_MAX_SCORES = 0
class DemoConfig(Config): class DemoConfig(Config):
# Main Configuration # Main Configuration
SCORE_FILE = 'demo.json' SCORE_FILE = 'demo.json'

View File

@@ -27,7 +27,9 @@ def create_app(env=None):
if app.config['DEMO']: if app.config['DEMO']:
app.logger.info('Generating Demo Data...') app.logger.info('Generating Demo Data...')
# Generate initial Demo data
utils.generateDemo() utils.generateDemo()
# Begin altering demo data regularly
scheduler.add_job(id='altering', func=utils.alterDemo, trigger="interval", seconds=app.config['DEMO_ALTERATION_INTERVAL']) scheduler.add_job(id='altering', func=utils.alterDemo, trigger="interval", seconds=app.config['DEMO_ALTERATION_INTERVAL'])
utils.refreshScores() utils.refreshScores()

View File

@@ -5,6 +5,7 @@ Stores important backend application functionality.
""" """
import json import json
import os import os
import time
import random import random
from collections import namedtuple from collections import namedtuple
from typing import List from typing import List
@@ -21,7 +22,7 @@ DATA_DIR = os.path.join(BASE_DIR, 'data')
SCORES_FILE = os.path.join(DATA_DIR, current_app.config['SCORE_FILE']) SCORES_FILE = os.path.join(DATA_DIR, current_app.config['SCORE_FILE'])
# Initialize global data/tracking vars # Initialize global data/tracking vars
lastChange: int = -1 lastChange: float = -1
teams: List[Team] = [] teams: List[Team] = []