serve.py
7.03 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
#!/opt/local/bin/python3.6
import os
import json
import random
import markdown
import tornado.ioloop
import tornado.web
from tornado import template
import questions
# markdown helper
def md(text):
return markdown.markdown(text,
extensions=[
'markdown.extensions.tables',
'markdown.extensions.fenced_code',
'markdown.extensions.codehilite',
'markdown.extensions.def_list',
'markdown.extensions.sane_lists'
])
# ----------------------------------------------------------------------------
class LearnApp(object):
def __init__(self):
self.factory = questions.QuestionFactory()
self.factory.load_files(['questions.yaml'], 'demo')
self.online = {}
self.q = None
# returns dictionary
def next_question(self):
# print('next question')
# q = self.factory.generate('math-expressions')
questions = list(self.factory)
# print(questions)
q = self.factory.generate(random.choice(questions))
# print(q)
self.q = q
return q
def login(self, uid):
print('LearnApp.login')
self.online[uid] = {
'name': 'john',
}
print(self.online)
# ----------------------------------------------------------------------------
class Application(tornado.web.Application):
def __init__(self):
settings = {
'template_path': os.path.join(os.path.dirname(__file__), 'templates'),
'static_path': os.path.join(os.path.dirname(__file__), 'static'),
'static_url_prefix': '/static/', # this is the default
'xsrf_cookies': False, # FIXME see how to do it...
'cookie_secret': '__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__', # FIXME
'login_url': '/login',
'debug': True,
}
handlers = [
(r'/', MainHandler),
(r'/login', LoginHandler),
(r'/logout', LogoutHandler),
(r'/learn', LearnHandler),
(r'/question', QuestionHandler),
]
super().__init__(handlers, **settings)
self.learn = LearnApp()
# ----------------------------------------------------------------------------
# Base handler common to all handlers.
class BaseHandler(tornado.web.RequestHandler):
@property
def learn(self):
return self.application.learn
def get_current_user(self):
user_cookie = self.get_secure_cookie("user")
# print('base.get_current_user -> ', user_cookie)
if user_cookie:
return user_cookie # json.loads(user_cookie)
# ----------------------------------------------------------------------------
class MainHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.redirect('/learn')
# ----------------------------------------------------------------------------
# /auth/login and /auth/logout
# ----------------------------------------------------------------------------
class LoginHandler(BaseHandler):
def get(self):
self.render('login.html')
def post(self):
print('login.post')
uid = self.get_body_argument('uid')
pw = self.get_body_argument('pw')
# FIXME check password ver examplo do blog tornado.
self.set_secure_cookie('user', uid)
self.application.learn.login(uid)
self.redirect('/learn')
# ----------------------------------------------------------------------------
class LogoutHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
name = tornado.escape.xhtml_escape(self.current_user)
print('logout '+name)
self.clear_cookie('user')
self.redirect(self.get_argument('next', '/'))
# ----------------------------------------------------------------------------
# /learn
# ----------------------------------------------------------------------------
class LearnHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
print('learn.get')
user = self.current_user.decode('utf-8')
# name = self.application.learn.online[user]
print(' user = '+str(user))
self.render('learn.html', name='aa', uid=user) # FIXME
# ----------------------------------------------------------------------------
# respond to AJAX to get a JSON question
class QuestionHandler(BaseHandler):
# @tornado.web.authenticated
# def get(self):
# question = self.application.learn.next_question()
# print('---> question.get')
# print(question)
# if question['type'] == 'checkbox':
# self.render('question-checkbox.html',
# question=question,
# md=md,
# )
# else:
# self.write('Error!!!')
@tornado.web.authenticated
def post(self):
print('---------------\nquestion.post')
# experiment answering one question and correct it
ref = self.get_body_arguments('question_ref')
print('Reference' + str(ref))
question = self.application.learn.q # get current question
print('=====================================')
print(' ' + str(question))
print('-------------------------------------')
if question is not None:
ans = self.get_body_arguments('answer')
print(' answer = ' + str(ans))
question['answer'] = ans # insert answer
grade = question.correct() # correct answer
print(' grade = ' + str(grade))
correct = grade > 0.99999
if correct:
question = self.application.learn.next_question()
else:
correct = True # to animate correctly
question = self.application.learn.next_question()
templates = {
'checkbox': 'question-checkbox.html',
'radio': 'question-radio.html',
'text': 'question-text.html',
'text_regex': 'question-text.html',
'text_numeric': 'question-text.html',
'textarea': 'question-textarea.html',
}
html_out = self.render_string(templates[question['type']],
question=question, # the dictionary with the question??
md=md, # passes function that renders markdown to html
)
self.write({
'html': tornado.escape.to_unicode(html_out),
'correct': correct,
})
# if question['type'] == 'checkbox':
# self.render('question-checkbox.html',
# question=question, # the dictionary with the question??
# md=md, # passes function that renders markdown to html
# )
# ----------------------------------------------------------------------------
def main():
server = Application()
server.listen(8080)
try:
print('--- start ---')
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.current().stop()
print('\n--- stop ---')
if __name__ == "__main__":
main()