app.py
9.57 KB
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
from os import path
import logging
import bcrypt
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from models import Base, Student, Test, Question
from contextlib import contextmanager # to create `with` statement for db sessions
import test
import threading
logger = logging.getLogger(__name__)
# ============================================================================
# Application
# ============================================================================
class App(object):
def __init__(self, filename, conf):
# online = {
# uid1: {
# 'student': {'number': 123, 'name': john, ...},
# 'test': {...}
# }
# uid2: {...}
# }
logger.info('============= Running perguntations =============')
self.lock = threading.Lock()
self.online = dict() # {uid: {'student':{}}}
self.allowed = set([]) # '0' is hardcoded to allowed elsewhere
self.testfactory = test.TestFactory(filename, conf=conf)
# database
engine = create_engine('sqlite:///{}'.format(self.testfactory['database']), echo=False)
Base.metadata.create_all(engine) # Criate schema if needed FIXME no student '0'
self.Session = scoped_session(sessionmaker(bind=engine))
try:
with self.db_session() as s:
n = s.query(Student).filter(Student.id != '0').count()
except Exception as e:
logger.critical('Database not usable {}.'.format(self.testfactory['database']))
raise e
else:
logger.info('Database has {} students registered.'.format(n))
# -----------------------------------------------------------------------
# helper to manage db sessions using the `with` statement, for example
# with self.db_session() as s: ...
@contextmanager
def db_session(self):
try:
yield self.Session()
finally:
self.Session.remove()
# -----------------------------------------------------------------------
def exit(self):
# FIXME what if there are online students?
logger.critical('----------- !!! Server terminated !!! -----------')
# -----------------------------------------------------------------------
def login(self, uid, try_pw):
if uid not in self.allowed and uid != '0':
# not allowed
logger.warning('Student {}: not allowed to login.'.format(uid))
return False
with self.db_session() as s:
student = s.query(Student).filter(Student.id == uid).one_or_none()
if student is None:
# not found
logger.warning('Student {}: not found in database.'.format(uid))
return False
if student.password == '':
# update password on first login
hashed_pw = bcrypt.hashpw(try_pw.encode('utf-8'), bcrypt.gensalt())
student.password = hashed_pw
s.commit()
logger.warning('Student {}: first login, password updated.'.format(uid))
elif bcrypt.hashpw(try_pw.encode('utf-8'), student.password) != student.password:
# wrong password
logger.info('Student {}: wrong password.'.format(uid))
return False
# success
self.allowed.discard(uid)
if uid in self.online:
logger.warning('Student {}: already logged in.'.format(uid))
else:
self.online[uid] = {'student': {'name': student.name, 'number': uid}}
logger.info('Student {}: logged in.'.format(uid))
return True
# -----------------------------------------------------------------------
def logout(self, uid):
if uid not in self.online:
# this should never happen
logger.error('Student {}: tried to logout, but is not logged in.'.format(uid))
return False
else:
logger.info('Student {}: logged out.'.format(uid))
del self.online[uid] # FIXME Nao está a gravar o teste como desistencia...
return True
# -----------------------------------------------------------------------
def generate_test(self, uid):
if uid in self.online:
logger.info('Student {}: generating new test.'.format(uid))
student_id = self.online[uid]['student']
self.lock.acquire() # FIXME is it needed?
self.online[uid]['test'] = self.testfactory.generate(student_id)
self.lock.release()
return self.online[uid]['test']
else:
logger.error('Student {}: offline, can''t generate test'.format(uid))
return None
# -----------------------------------------------------------------------
def correct_test(self, uid, ans):
t = self.online[uid]['test']
t.update_answers(ans)
grade = t.correct()
logger.info('Student {0}: finished with {1} points.'.format(uid, grade))
if t['save_answers']:
fname = ' -- '.join((t['student']['number'], t['ref'], str(t['finish_time']))) + '.json'
fpath = path.abspath(path.join(t['answers_dir'], fname))
t.save_json(fpath)
with self.db_session() as s:
s.add(Test(
ref=t['ref'],
grade=t['grade'],
starttime=str(t['start_time']),
finishtime=str(t['finish_time']),
student_id=t['student']['number']))
s.add_all([Question(
ref=q['ref'],
grade=q['grade'],
starttime='',
finishtime=str(t['finish_time']),
student_id=t['student']['number'],
test_id=t['ref']) for q in t['questions'] if 'grade' in q])
s.commit()
return grade
# -----------------------------------------------------------------------
def giveup_test(self, uid):
logger.info('Student {0}: gave up.'.format(uid))
t = self.online[uid]['test']
t.giveup()
if t['save_answers']:
fname = ' -- '.join((t['student']['number'], t['ref'], str(t['finish_time']))) + '.json'
fpath = path.abspath(path.join(t['answers_dir'], fname))
t.save_json(fpath)
# -----------------------------------------------------------------------
# --- helpers (getters)
def get_student_name(self, uid):
return self.online[uid]['student']['name']
def get_test(self, uid, default=None):
return self.online[uid].get('test', default)
def get_test_qtypes(self, uid):
return {q['ref']:q['type'] for q in self.online[uid]['test']['questions']}
def get_student_grades_from_all_tests(self, uid):
with self.db_session() as s:
r = s.query(Test).filter(Student.id == uid).all()
return [(t.id, t.grade, t.finishtime) for t in r]
def get_online_students(self):
# [('uid', 'name', 'starttime')]
return [(k, v['student']['name'], str(v.get('test', {}).get('start_time', '---'))) for k,v in self.online.items() if k != '0']
def get_offline_students(self):
# list of ('uid', 'name') sorted by uid
return [u[:2] for u in self.get_all_students() if u[0] not in self.online]
def get_all_students(self):
# list of all ('uid', 'name', 'password') sorted by uid
with self.db_session() as s:
r = s.query(Student).all()
return sorted(((u.id, u.name, u.password) for u in r if u.id != '0'), key=lambda k: k[0])
def get_student_grades_from_test(self, uid, testid):
with self.db_session() as s:
r = s.query(Test).filter(Test.student_id==uid and Test.id==testid).all()
return [(u.grade, u.finishtime) for u in r]
def get_students_state(self):
# [{
# 'uid' : '12345'
# 'name' : 'John Smith',
# 'start_time': '',
# 'grades' : [10.2, 13.1],
# ...
# }]
l = []
for u in self.get_all_students():
uid, name, pw = u
l.append({
'uid': uid,
'name': name,
'allowed': uid in self.allowed,
'online': uid in self.online,
'start_time': self.online.get(uid, {}).get('test', {}).get('start_time',''),
'password_defined': pw != '',
'grades': self.get_student_grades_from_test(uid, self.testfactory['ref']),
'ip_address': self.online.get(uid, {}).get('student', {}).get('ip_address',''),
'user_agent': self.online.get(uid, {}).get('student', {}).get('user_agent','')
})
return l
def get_allowed_students(self):
# set of 'uid' allowed to login
return self.allowed
# --- helpers (change state)
def allow_student(self, uid):
self.allowed.add(uid)
logger.info('Student {}: allowed to login.'.format(uid))
def deny_student(self, uid):
self.allowed.discard(uid)
logger.info('Student {}: denied to login'.format(uid))
def reset_password(self, uid):
with self.db_session() as s:
u = s.query(Student).filter(Student.id == uid).update({'password': ''})
s.commit()
logger.info('Student {}: password reset to ""'.format(uid))
def set_user_agent(self, uid, user_agent=''):
self.online[uid]['student']['user_agent'] = user_agent
def set_user_ip(self, uid, ipaddress=''):
self.online[uid]['student']['ip_address'] = ipaddress