-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
150 lines (125 loc) · 4.78 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from flask import Flask, render_template, request, redirect, url_for, session
import atexit
import json
from datetime import datetime
import csv
from dotenv import load_dotenv
import os
import logging
from stats_updater import StatsUpdater
from pathlib import Path
load_dotenv()
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
app.config['PREFERRED_URL_SCHEME'] = 'https'
# Initialize and start the stats updater
stats_updater = StatsUpdater(update_interval=300) # 5 minutes
stats_updater.start()
# Register a function to stop the updater when the app stops
@atexit.register
def shutdown_stats_updater():
stats_updater.stop()
return app
@app.after_request
def add_security_headers(response):
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"img-src 'self' data: https:; " # Allow HTTPS images
"connect-src 'self' https:; "
"font-src 'self' data: https:;"
)
return response
# Set data directory
DATA_DIR = os.getenv('DATA_DIR', '/app/data')
os.makedirs(DATA_DIR, exist_ok=True)
logging.basicConfig(level=logging.DEBUG)
def log_debug_info():
logging.debug(f"Current working directory: {os.getcwd()}")
logging.debug(f"Contents of current directory: {os.listdir('.')}")
logging.debug(f"Contents of /app/data: {os.listdir('/app/data')}")
logging.debug(f"Current user: {os.getuid()}:{os.getgid()}")
logging.debug(f"DATA_DIR environment variable: {os.getenv('DATA_DIR')}")
log_debug_info()
# Load quiz configuration
def load_quiz_config():
with open('config.json', 'r') as f:
return json.load(f)
# Routes
@app.route('/')
def index():
quizzes = load_quiz_config()
return render_template('index.html', quizzes=quizzes)
@app.route('/start_quiz', methods=['POST'])
def start_quiz():
quiz_id = int(request.form['quiz_id'])
user_id = request.form['user_id']
session['user_id'] = user_id
session['current_image_index'] = 0
return redirect(url_for('quiz', quiz_id=quiz_id))
@app.route('/quiz/<int:quiz_id>')
def quiz(quiz_id):
if 'user_id' not in session:
return redirect(url_for('index'))
quizzes = load_quiz_config()
if quiz_id < len(quizzes):
quiz = quizzes[quiz_id]
current_image_index = session.get('current_image_index', 0)
if current_image_index < len(quiz['images']):
# Process all image URLs at once
processed_quiz = quiz.copy()
processed_quiz['images'] = [
{
**img,
'url': url_for('static', filename=img['url'].replace('/static/', ''))
}
for img in quiz['images']
]
return render_template('quiz.html',
quiz=processed_quiz,
image_index=current_image_index)
else:
return redirect(url_for('thank_you'))
else:
return "Quiz not found", 404
@app.route('/submit_answer', methods=['POST'])
def submit_answer():
if 'user_id' not in session:
return redirect(url_for('index', _scheme='https', _external=True))
user_id = session['user_id']
answer = request.form['answer']
quiz_id = int(request.form['quiz_id'])
image_index = int(request.form['image_index'])
response_time = float(request.form['response_time'])
save_answer(user_id, quiz_id, image_index, answer, response_time)
session['current_image_index'] = image_index + 1
return redirect(url_for('quiz', quiz_id=quiz_id))
@app.route('/complete')
def thank_you():
return render_template('complete.html')
def save_answer(user_id, quiz_id, image_index, answer, response_time):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
results_file = os.path.join(DATA_DIR, 'results.csv')
file_exists = os.path.isfile(results_file)
logging.debug(f"Results file: {results_file}")
try:
with open(results_file, 'a', newline='') as file:
writer = csv.writer(file)
if not file_exists:
writer.writerow(['Timestamp', 'User ID', 'Quiz ID', 'Image Index', 'Answer', 'Response Time'])
writer.writerow([timestamp, user_id, quiz_id, image_index, answer, response_time])
logging.debug(f"Saved answer to {results_file}")
except Exception as e:
logging.error(f"Error writing to file: {str(e)}")
raise
@app.route('/statistics')
def statistics():
return render_template(
'statistics.html',
datetime=datetime,
path=Path,
static_folder=app.static_folder
)
if __name__ == '__main__':
app.run(debug=True)