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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
from yaksh.models import (
Question, Quiz, QuestionPaper, QuestionSet, AnswerPaper, Course, Answer
)
from api.serializers import (
QuestionSerializer, QuizSerializer, QuestionPaperSerializer,
AnswerPaperSerializer, CourseSerializer
)
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from rest_framework.authtoken.models import Token
from rest_framework.decorators import (
api_view, authentication_classes, permission_classes
)
from django.http import Http404
from django.contrib.auth import authenticate
from yaksh.code_server import get_result as get_result_from_code_server
from yaksh.settings import SERVER_POOL_PORT, SERVER_HOST_NAME
import json
class QuestionList(APIView):
""" List all questions or create a new question. """
def get(self, request, format=None):
questions = Question.objects.filter(user=request.user)
serializer = QuestionSerializer(questions, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = QuestionSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CourseList(APIView):
""" List all courses """
def get(self, request, format=None):
courses = Course.objects.filter(students=request.user)
serializer = CourseSerializer(courses, many=True)
return Response(serializer.data)
class StartQuiz(APIView):
""" Retrieve Answerpaper. If does not exists then create one """
def get_quiz(self, pk, user):
try:
return Quiz.objects.get(pk=pk)
except Quiz.DoesNotExist:
raise Http404
def get(self, request, course_id, quiz_id, format=None):
context = {}
user = request.user
quiz = self.get_quiz(quiz_id, user)
questionpaper = quiz.questionpaper_set.first()
last_attempt = AnswerPaper.objects.get_user_last_attempt(
questionpaper, user, course_id)
if last_attempt and last_attempt.is_attempt_inprogress():
serializer = AnswerPaperSerializer(last_attempt)
context["time_left"] = last_attempt.time_left()
context["answerpaper"] = serializer.data
return Response(context)
can_attempt, msg = questionpaper.can_attempt_now(user, course_id)
if not can_attempt:
return Response({'message': msg})
if not last_attempt:
attempt_number = 1
else:
attempt_number = last_attempt.attempt_number + 1
ip = request.META['REMOTE_ADDR']
answerpaper = questionpaper.make_answerpaper(user, ip, attempt_number,
course_id)
serializer = AnswerPaperSerializer(answerpaper)
context["time_left"] = answerpaper.time_left()
context["answerpaper"] = serializer.data
return Response(context, status=status.HTTP_201_CREATED)
class QuestionDetail(APIView):
""" Retrieve, update or delete a question """
def get_question(self, pk, user):
try:
return Question.objects.get(pk=pk, user=user)
except Question.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
question = self.get_question(pk, request.user)
serializer = QuestionSerializer(question)
return Response(serializer.data)
def put(self, request, pk, format=None):
question = self.get_question(pk, request.user)
serializer = QuestionSerializer(question, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
question = self.get_question(pk, request.user)
question.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class AnswerPaperList(APIView):
def get_questionpaper(self, pk):
try:
return QuestionPaper.objects.get(pk=pk)
except QuestionPaper.DoesNotExist:
raise Http404
def get_course(self, pk):
try:
return Course.objects.get(pk=pk)
except Course.DoesNotExist:
raise Http404
def get_answerpapers(self, user):
return AnswerPaper.objects.filter(question_paper__quiz__creator=user)
def get(self, request, format=None):
user = request.user
answerpapers = self.get_answerpapers(user)
serializer = AnswerPaperSerializer(answerpapers, many=True)
return Response(serializer.data)
def is_user_allowed(self, user, course):
''' if user is student or teacher or creator then allow '''
return user in course.students.all() or user in course.teachers.all() \
or user == course.creator
def post(self, request, format=None):
try:
questionpaperid = request.data['question_paper']
attempt_number = request.data['attempt_number']
course_id = request.data['course']
except KeyError:
return Response(status=status.HTTP_400_BAD_REQUEST)
user = request.user
ip = request.META['REMOTE_ADDR']
questionpaper = self.get_questionpaper(questionpaperid)
course = self.get_course(course_id)
if not self.is_user_allowed(user, course):
return Response(status=status.HTTP_400_BAD_REQUEST)
answerpaper = questionpaper.make_answerpaper(user, ip, attempt_number,
course_id)
serializer = AnswerPaperSerializer(answerpaper)
return Response(serializer.data, status=status.HTTP_201_CREATED)
class AnswerValidator(APIView):
def get_answerpaper(self, pk, user):
try:
return AnswerPaper.objects.get(pk=pk, user=user)
except AnswerPaper.DoesNotExist:
raise Http404
def get_question(self, pk, answerpaper):
try:
question = Question.objects.get(pk=pk)
if question in answerpaper.questions.all():
return question
else:
raise Http404
except AnswerPaper.DoesNotExist:
raise Http404
def get_answer(self, pk):
try:
return Answer.objects.get(pk=pk)
except Answer.DoesNotExist:
raise Http404
def post(self, request, answerpaper_id, question_id, format=None):
try:
user_answer = str(request.data['answer'])
except KeyError:
return Response(status=status.HTTP_400_BAD_REQUEST)
user = request.user
answerpaper = self.get_answerpaper(answerpaper_id, user)
question = self.get_question(question_id, answerpaper)
# save answer uid
answer = Answer.objects.create(question=question, answer=user_answer)
answerpaper.answers.add(answer)
answerpaper.save()
json_data = None
if question.type in ['code', 'upload']:
json_data = question.consolidate_answer_data(user_answer, user)
result = answerpaper.validate_answer(user_answer, question, json_data,
answer.id)
# updaTE RESult
if question.type not in ['code', 'upload']:
if result.get('success'):
answer.correct = True
answer.marks = question.points
answer.error = json.dumps(result.get('error'))
answer.save()
answerpaper.update_marks(state='inprogress')
return Response(result)
def get(self, request, uid):
answer = self.get_answer(uid)
url = '{0}:{1}'.format(SERVER_HOST_NAME, SERVER_POOL_PORT)
result = get_result_from_code_server(url, uid)
# update result
if result['status'] == 'done':
final_result = json.loads(result.get('result'))
answer.error = json.dumps(final_result.get('error'))
if final_result.get('success'):
answer.correct = True
answer.marks = answer.question.points
answer.save()
answerpaper = answer.answerpaper_set.get()
answerpaper.update_marks(state='inprogress')
return Response(result)
class QuizList(APIView):
""" List all quizzes or create a new quiz """
def get(self, request, format=None):
quizzes = Quiz.objects.filter(creator=request.user)
serializer = QuizSerializer(quizzes, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = QuizSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class QuizDetail(APIView):
""" Retrieve, update or delete a quiz """
def get_quiz(self, pk, user):
try:
return Quiz.objects.get(pk=pk, creator=user)
except Quiz.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
quiz = self.get_quiz(pk, request.user)
serializer = QuizSerializer(quiz)
return Response(serializer.data)
def put(self, request, pk, format=None):
quiz = self.get_quiz(pk, request.user)
serializer = QuizSerializer(quiz, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
quiz = self.get_quiz(pk, request.user)
quiz.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class QuestionPaperList(APIView):
""" List all question papers or create a new question paper """
def get_questionpapers(self, user):
return QuestionPaper.objects.filter(quiz__creator=user)
def questionpaper_exists(self, quiz_id):
return QuestionPaper.objects.filter(quiz=quiz_id).exists()
def check_quiz_creator(self, user, quiz_id):
try:
Quiz.objects.get(pk=quiz_id, creator=user)
except Quiz.DoesNotExist:
raise Http404
def check_questions_creator(self, user, question_ids):
for question_id in question_ids:
try:
Question.objects.get(pk=question_id, user=user)
except Question.DoesNotExist:
raise Http404
def check_questionsets_creator(self, user, questionset_ids):
for question_id in questionset_ids:
try:
questionset = QuestionSet.objects.get(pk=question_id)
for question in questionset.questions.all():
Question.objects.get(pk=question.id, user=user)
except (QuestionSet.DoesNotExist, Question.DoesNotExist):
raise Http404
def get(self, request, format=None):
questionpapers = self.get_questionpapers(request.user)
serializer = QuestionPaperSerializer(questionpapers, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = QuestionPaperSerializer(data=request.data)
if serializer.is_valid():
user = request.user
quiz_id = request.data.get('quiz')
question_ids = request.data.get('fixed_questions', [])
questionset_ids = request.data.get('random_questions', [])
if self.questionpaper_exists(quiz_id):
return Response({'error': 'Already exists'},
status=status.HTTP_409_CONFLICT)
self.check_quiz_creator(user, quiz_id)
self.check_questions_creator(user, question_ids)
self.check_questionsets_creator(user, questionset_ids)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
class QuestionPaperDetail(APIView):
""" Retrieve, update or delete a question paper"""
def get_questionpaper(self, pk, user):
try:
return QuestionPaper.objects.get(pk=pk, quiz__creator=user)
except QuestionPaper.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
questionpaper = self.get_questionpaper(pk, request.user)
serializer = QuestionPaperSerializer(questionpaper)
return Response(serializer.data)
def check_quiz_creator(self, user, quiz_id):
try:
Quiz.objects.get(pk=quiz_id, creator=user)
except Quiz.DoesNotExist:
raise Http404
def check_questions_creator(self, user, question_ids):
for question_id in question_ids:
try:
Question.objects.get(pk=question_id, user=user)
except Question.DoesNotExist:
raise Http404
def check_questionsets_creator(self, user, questionset_ids):
for question_id in questionset_ids:
try:
questionset = QuestionSet.objects.get(pk=question_id)
for question in questionset.questions.all():
Question.objects.get(pk=question.id, user=user)
except (QuestionSet.DoesNotExist, Question.DoesNotExist):
raise Http404
def put(self, request, pk, format=None):
user = request.user
questionpaper = self.get_questionpaper(pk, user)
serializer = QuestionPaperSerializer(questionpaper, data=request.data)
if serializer.is_valid():
user = request.user
quiz_id = request.data.get('quiz')
question_ids = request.data.get('fixed_questions', [])
questionset_ids = request.data.get('random_questions', [])
self.check_quiz_creator(user, quiz_id)
self.check_questions_creator(user, question_ids)
self.check_questionsets_creator(user, questionset_ids)
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
questionpaper = self.get_questionpaper(pk, request.user)
questionpaper.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class GetCourse(APIView):
def get(self, request, pk, format=None):
course = Course.objects.get(id=pk)
serializer = CourseSerializer(course)
return Response(serializer.data)
@api_view(['POST'])
@authentication_classes(())
@permission_classes(())
def login(request):
data = {}
if request.method == "POST":
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user is not None and user.is_authenticated:
token, created = Token.objects.get_or_create(user=user)
data = {
'token': token.key
}
return Response(data, status=status.HTTP_201_CREATED)
class QuitQuiz(APIView):
def get_answerpaper(self, answerpaper_id):
try:
return AnswerPaper.objects.get(id=answerpaper_id)
except AnswerPaper.DoesNotExist:
raise Http404
def get(self, request, answerpaper_id, format=None):
answerpaper = self.get_answerpaper(answerpaper_id)
answerpaper.status = 'completed'
answerpaper.save()
serializer = AnswerPaperSerializer(answerpaper)
return Response(serializer.data)
|