more configuration implementation, beginnings of demo app mode, switch to flask-apscheduler for proper app context (jank)

This commit is contained in:
Xevion
2020-06-20 19:53:29 -05:00
parent a2bde58ace
commit fda4d89440
5 changed files with 69 additions and 42 deletions
-8
View File
@@ -1,8 +0,0 @@
from setuptools import setup
setup(
name='flask-demo',
entry_points= {
'con'
}
)
+2 -2
View File
@@ -1,5 +1,5 @@
from create_app import create_app from trivia.create_app import create_app
if __name__ == '__main__': if __name__ == '__main__':
app = create_app() app = create_app()
app.run() app.run()
+11 -1
View File
@@ -12,11 +12,21 @@ configs = {
class Config(object): class Config(object):
# Main Configuration
SCORE_FILE = 'scores.json' SCORE_FILE = 'scores.json'
DEMO = False POLLING_INTERVAL = 5
# Demo Configuration
DEMO = False
DEMO_TEAM_COUNT = 0
DEMO_ALTERATION_INTERVAL = 0
class DemoConfig(Config): class DemoConfig(Config):
# Main Configuration
SCORE_FILE = 'demo.json' SCORE_FILE = 'demo.json'
# Demo Configuration
DEMO = True DEMO = True
DEMO_TEAM_COUNT = 30
DEMO_ALTERATION_INTERVAL = 15
+18 -7
View File
@@ -1,9 +1,9 @@
from apscheduler.schedulers.background import BackgroundScheduler from flask_apscheduler import APScheduler
from flask import Flask from flask import Flask
from trivia import utils
from trivia.config import configs from trivia.config import configs
scheduler: APScheduler = None
def create_app(env=None): def create_app(env=None):
app = Flask(__name__) app = Flask(__name__)
@@ -12,12 +12,23 @@ def create_app(env=None):
env = app.config['ENV'] env = app.config['ENV']
app.config.from_object(configs[env]) app.config.from_object(configs[env])
# Setup a scheduler for automatically refreshing data
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(func=utils.refreshScores, trigger="interval", seconds=5)
with app.app_context(): with app.app_context():
# noinspection PyUnresolvedReferences
from trivia import routes, api, utils
# Setup a scheduler for automatically refreshing data
global scheduler
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
# Add score file polling
scheduler.add_job(id='polling', func=utils.refreshScores, trigger="interval", seconds=app.config['POLLING_INTERVAL'])
if app.config['DEMO']:
app.logger.info('Generating Demo Data...')
utils.generateDemo()
utils.refreshScores() utils.refreshScores()
return app return app
+38 -24
View File
@@ -9,7 +9,7 @@ from collections import namedtuple
from typing import List from typing import List
# Simple fake 'class' for passing to jinja templates # Simple fake 'class' for passing to jinja templates
# from trivia import app import faker as faker
from flask import current_app from flask import current_app
Team = namedtuple('Team', ['id', 'name', 'scores']) Team = namedtuple('Team', ['id', 'name', 'scores'])
@@ -17,7 +17,7 @@ Team = namedtuple('Team', ['id', 'name', 'scores'])
# Generate paths # Generate paths
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, 'data') DATA_DIR = os.path.join(BASE_DIR, 'data')
SCORES_FILE = os.path.join(DATA_DIR, 'scores.json') 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: int = -1
@@ -41,33 +41,47 @@ def refreshScores() -> None:
global lastChange global lastChange
curChange = lastModified() curChange = lastModified()
if lastChange < curChange: from trivia.create_app import scheduler
try: app = scheduler.app
# Update tracking var
lastChange = curChange
current_app.logger.debug('Attempting to load and parse scores file.') with app.app_context():
with open(SCORES_FILE) as file: if lastChange < curChange:
temp = json.load(file) try:
# Update tracking var
lastChange = curChange
# Place all values into Team object for jinja current_app.logger.debug('Attempting to load and parse scores file.')
temp = [ with open(SCORES_FILE, 'r') as file:
Team( temp = json.load(file)
id=team['teamno'],
name=team['teamname'],
scores=team['scores']
) for team in temp
]
current_app.logger.debug(f'Successfully loaded ({len(temp)} teams).')
global teams # Place all values into Team object for jinja
teams = temp temp = [
Team(
id=team['teamno'],
name=team['teamname'],
scores=team['scores']
) for team in temp
]
current_app.logger.debug(f'Successfully loaded ({len(temp)} teams).')
# If invalid or inaccessible, simply do nothing. global teams
except json.JSONDecodeError: teams = temp
current_app.logger.error('Scores file could not be opened or parsed.', print_exc=True)
# If invalid or inaccessible, simply do nothing.
except json.JSONDecodeError:
current_app.logger.error('Scores file could not be opened or parsed.', print_exc=True)
def generateDemo() -> None: def generateDemo() -> None:
pass fake = faker.Faker()
data = [
{
'teamno': i + 1,
'teamname': fake.user_name(),
'scores': []
} for i in range(current_app.config['DEMO_TEAM_COUNT'])
]
with open(SCORES_FILE, 'w') as file:
json.dump(data, file)