website/events/app.py
Jimmy Vargo dae67ce653 Update Events (#10)
This update restructures the events page code and provides additional functionality.
- Overwrite old entries on re-submission of previously used emails
- Build data and stats caches on launch for use in submission checks and stats regeneration
- Update to form content
- Move stats function to separate utils file

Reviewed-on: ayo/website#10
Co-authored-by: Jimmy Vargo <james@ayo.tokyo>
Co-committed-by: Jimmy Vargo <james@ayo.tokyo>
2024-05-07 18:59:57 +09:00

62 lines
1.8 KiB
Python

from datetime import datetime
import json
from pathlib import Path
from flask import Flask, request, render_template
from form_content import FormContent
from utils import get_data_stats
app = Flask(__name__)
save_path = Path('data.json')
data_cache = { entry['email']: entry for entry in json.loads(save_path.read_text()) }\
if save_path.exists() else {}
stats_cache = get_data_stats(data_cache)
MAX_FILE_SIZE = 1_000_000
MAX_REQUEST_LENGTH = 1_000
@app.route('/')
def form():
return render_template('form.html',
times=FormContent.times,
topics=FormContent.topics,
background=FormContent.background,
languages=FormContent.languages)
@app.route('/submit', methods=['POST'])
def submit():
if save_path.exists() and save_path.stat().st_size > MAX_FILE_SIZE:
return { 'error': 'Database full.' }, 500
if len(request.data) > MAX_REQUEST_LENGTH:
return { 'error': 'Request too long.' }, 400
data = request.get_json()
if set(data) != FormContent.all_keys:
return { 'error': 'Invalid request format.' }, 400
data['date_submitted'] = datetime.strftime(datetime.now(), '%Y/%m/%d, %H:%M:%S')
data_cache[data['email']] = data
save_path.write_text(json.dumps(list(data_cache.values()), indent='\t'))
global stats_cache
stats_cache = get_data_stats(data_cache)
return {}, 200
@app.route('/stats')
def stats():
return render_template('stats.html',
times=FormContent.times,
topics=FormContent.topics,
background=FormContent.background,
languages=FormContent.languages,
data=stats_cache)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9700, debug=False)