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
|
import random
import sys
import traceback
import string
from django.db import IntegrityError
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from exam.models import Question, Quiz, Profile, Answer
from exam.forms import UserRegisterForm
def gen_key(no_of_chars):
"""Generate a random key of the number of characters."""
allowed_chars = string.digits+string.uppercase
return ''.join([random.choice(allowed_chars) for i in range(no_of_chars)])
def index(request):
"""The start page.
"""
# Largely copied from Nishanth's quiz app.
user = request.user
if user.is_authenticated():
return redirect("/exam/start/")
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
while True:
try:
username = gen_key(20)
new_user = User.objects.create_user(username, "temp@temp.com", "123")
break
except IntegrityError:
pass
new_user.first_name = data['first_name']
new_user.last_name = data['last_name']
new_user.save()
new_profile = Profile(user=new_user)
new_profile.roll_number = data['roll_number']
new_profile.save()
user = authenticate(username=username, password="123")
login(request, user)
return redirect("/exam/start/")
else:
return render_to_response('exam/register.html',{'form':form},
context_instance=RequestContext(request))
else:
form = UserRegisterForm()
return render_to_response('exam/register.html',{'form':form},
context_instance=RequestContext(request))
def show_question(request, q_id):
"""Show a question if possible."""
if len(q_id) == 0:
return redirect("/exam/complete")
else:
return question(request, q_id)
def start(request):
user = request.user
try:
old_quiz = Quiz.objects.get(user=user)
q = old_quiz.current_question()
return redirect('/exam/%s'%q)
except Quiz.DoesNotExist:
ip = request.META['REMOTE_ADDR']
key = gen_key(10)
new_quiz = Quiz(user=user, user_ip=ip, key=key)
questions = [ str(_.id) for _ in Question.objects.all() ]
random.shuffle(questions)
questions = questions[:3]
new_quiz.questions = "|".join(questions)
new_quiz.save()
q = new_quiz.current_question()
return show_question(request, q)
def question(request, q_id):
q = get_object_or_404(Question, pk=q_id)
try:
quiz = Quiz.objects.get(user=request.user)
except Quiz.DoesNotExist:
redirect('/exam/start')
context = {'question': q, 'quiz': quiz}
ci = RequestContext(request)
return render_to_response('exam/question.html', context,
context_instance=ci)
def test_python(answer, test_code):
"""Tests given Python function with the test code supplied.
Returns
-------
A tuple: (success, error message).
"""
success = False
tb = None
try:
submitted = compile(answer, '<string>', mode='exec')
g = {}
exec submitted in g
_tests = compile(test_code, '<string>', mode='exec')
exec _tests in g
except AssertionError:
type, value, tb = sys.exc_info()
info = traceback.extract_tb(tb)
fname, lineno, func, text = info[-1]
text = str(test_code).splitlines()[lineno-1]
err = "{0} {1} in: {2}".format(type.__name__, str(value), text)
except:
type, value = sys.exc_info()[:2]
err = "Error: {0}".format(repr(value))
else:
success = True
err = 'Correct answer'
finally:
del tb
return success, err
def check(request, q_id):
user = request.user
question = get_object_or_404(Question, pk=q_id)
quiz = Quiz.objects.get(user=user)
answer = request.POST.get('answer')
skip = request.POST.get('skip', None)
if skip is not None:
next_q = quiz.skip()
return show_question(request, next_q)
# Otherwise we were asked to check.
success, err_msg = test_python(answer, question.test)
# Add the answer submitted.
new_answer = Answer(question=question, answer=answer.strip())
new_answer.correct = success
new_answer.save()
quiz.answers.add(new_answer)
ci = RequestContext(request)
if not success:
context = {'question': question, 'error_message': err_msg,
'last_attempt': answer}
return render_to_response('exam/question.html', context,
context_instance=ci)
else:
next_q = quiz.answered_question(question.id)
return show_question(request, next_q)
def quit(request):
return render_to_response('exam/quit.html',
context_instance=RequestContext(request))
def complete(request):
yes = True
if request.method == 'POST':
yes = request.POST.get('yes', None)
if yes:
logout(request)
return render_to_response('exam/complete.html')
else:
return redirect('/exam/')
def monitor(request):
"""Monitor the progress of the quizzes taken so far."""
quizzes = Quiz.objects.all()
questions = Question.objects.all()
# Mapping from question id to points
marks = dict( ( (q.id, q.points) for q in questions) )
quiz_list = []
for quiz in quizzes:
paper = {}
user = quiz.user
paper['username'] = str(user.first_name) + ' ' + str(user.last_name)
paper['rollno'] = str(Profile.objects.get(user=user).roll_number)
qa = quiz.questions_answered.split('|')
answered = ', '.join(sorted(qa))
paper['answered'] = answered if answered else 'None'
total = sum( [marks[int(id)] for id in qa if id] )
paper['total'] = total
quiz_list.append(paper)
quiz_list.sort(cmp=lambda x, y: cmp(x['total'], y['total']),
reverse=True)
context = {'quiz_list': quiz_list}
return render_to_response('exam/monitor.html', context,
context_instance=RequestContext(request))
|