views.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. # coding=utf-8
  2. import json
  3. import traceback
  4. from django.utils import timezone
  5. from rest_framework.decorators import action
  6. from django.db import transaction
  7. from django.db.models import F
  8. from utils.custom_modelviewset import CustomModelViewSet
  9. from utils import response_ok, response_error
  10. from utils.permission import IsStaff
  11. from apps.examination.exam.serializers import *
  12. from apps.examination.exam.filters import *
  13. from apps.system.models import SysLog
  14. from apps.examination.exam.models import ExamAnswerLog, ExamAnswerOptionLog, ExamAnswerFillLog
  15. from apps.examination.exampaper.models import ExamPaperDetail, ExamQuestion
  16. from apps.examination.examquestion.models import ExamQuestionOption, ExamQuestionFill, ExamQuestionFeedback
  17. from apps.examination.examquestion.serializers import ExamQuestionFeedbackSerializer
  18. from apps.practise.errorbook.models import ErrorBook
  19. from utils.format import strftime
  20. class ExamLogViewSet(CustomModelViewSet):
  21. permission_classes = [IsStaff, ]
  22. queryset = ExamLog.objects.filter(delete=False, type=ExamLog.FORMAL,)
  23. serializer_class = StaffExamLogSerializer
  24. def filter_queryset(self, queryset):
  25. queryset = queryset.filter(user=self.request.user)
  26. return queryset
  27. def retrieve(self, request, *args, **kwargs):
  28. instance = self.get_object()
  29. serializer = StaffExamLogRetrieveSerializer(instance)
  30. answer_log = []
  31. answer_logs = ExamAnswerLog.objects.filter(main=instance).order_by('detail__order')
  32. for al in answer_logs:
  33. item = {
  34. 'id':al.id,
  35. 'status':al.status,
  36. }
  37. answer_log.append(item)
  38. result = {
  39. 'question': serializer.data,
  40. 'answer_log': answer_log,
  41. 'ranks': [],
  42. }
  43. return response_ok(result)
  44. @action(methods=['get'], detail=False)
  45. def get_exam(self, request):
  46. start_time = timezone.now() + datetime.timedelta(minutes=30)
  47. queryset = ExamLog.objects.filter(delete=False,
  48. type=ExamLog.FORMAL,
  49. exam__exam_time__lte=start_time,
  50. user=request.user,
  51. exam__exam_end_time__gte=timezone.now()
  52. )
  53. data = []
  54. for exam_log in queryset:
  55. item = {
  56. 'id':exam_log.id,
  57. 'name':exam_log.exam.name,
  58. 'subject':exam_log.exam.subject.name,
  59. 'exam_time':strftime(exam_log.exam.exam_time),
  60. 'exam_end_time':strftime(exam_log.exam.exam_end_time),
  61. 'duration':exam_log.exam.duration,
  62. }
  63. data.append(item)
  64. return response_ok(data)
  65. @action(methods=['post'], detail=True)
  66. def get_next_practise(self, request, pk):
  67. now_practise = request.data.get('now_practise') # 当前提交的模拟考试明细id。第一题或继续答题时,该参数为空
  68. answers = json.loads(request.data.get('answers')) # 答案, 第一题或继续答题时,该参数为空
  69. next_practise = request.data.get('next_practise') # 下一题id,首次加载第一题,传空
  70. try:
  71. with transaction.atomic():
  72. instance = self.get_object()
  73. # 点击下一题,保存
  74. if now_practise:
  75. detail = ExamPaperDetail.objects.filter(id=now_practise).first()
  76. if not detail:
  77. raise CustomError('提交的考试习题有误,请刷新重试!')
  78. now_question = detail.question
  79. if len(answers) > 0:
  80. answer_log, create = ExamAnswerLog.objects.get_or_create(main=instance,
  81. detail=detail, )
  82. if now_question.type <= ExamQuestion.MULTIPLE:
  83. # 单选、多选
  84. answers.sort()
  85. ExamAnswerOptionLog.objects.filter(main=answer_log).delete()
  86. for a in answers:
  87. ExamAnswerOptionLog.objects.create(main=answer_log, option_id=a)
  88. elif now_question.type == ExamQuestion.FILL:
  89. # 填空
  90. answers_len = len(answers)
  91. ExamAnswerFillLog.objects.filter(main=answer_log).delete()
  92. for a in range(0, answers_len):
  93. ExamAnswerFillLog.objects.create(main=answer_log, content=answers[a], order=a + 1)
  94. else:
  95. # 判断
  96. if answers[0] == 1:
  97. answer_log.status = ExamAnswerLog.RIGHT
  98. else:
  99. answer_log.status = ExamAnswerLog.WRONG
  100. answer_log.save()
  101. else:
  102. try:
  103. answer_log = ExamAnswerLog.objects.get(main=instance, detail=detail)
  104. ExamAnswerOptionLog.objects.filter(main=answer_log).delete()
  105. ExamAnswerFillLog.objects.filter(main=answer_log).delete()
  106. answer_log.status = ExamAnswerLog.NOTDONE
  107. answer_log.save()
  108. except ExamAnswerLog.DoesNotExist:
  109. # traceback.print_exc()
  110. pass
  111. question_data = {}
  112. # 返回下一题
  113. if next_practise:
  114. detail = ExamPaperDetail.objects.filter(id=next_practise, main=instance.exampaper,
  115. delete=False).first()
  116. else:
  117. detail = ExamPaperDetail.objects.filter(main=instance.exampaper, delete=False).first()
  118. if detail:
  119. question = detail.question
  120. question_data = {
  121. 'id': detail.id,
  122. 'title': question.title,
  123. 'next_type': question.type, # 下一题习题类别
  124. 'next_number': detail.order + 1, # 下下一题序号,
  125. 'option': [],
  126. }
  127. answer_log = ExamAnswerLog.objects.filter(main=instance, detail=detail).first()
  128. if question.type == ExamQuestion.JUDGMENT:
  129. item1 = {
  130. 'id': 1,
  131. 'content': '正确',
  132. 'answer': True if answer_log and answer_log.status == ExamAnswerLog.RIGHT else False
  133. }
  134. item0 = {
  135. 'id': 0,
  136. 'content': '错误',
  137. 'answer': True if answer_log and answer_log.status == ExamAnswerLog.WRONG else False
  138. }
  139. question_data['option'].append(item1)
  140. question_data['option'].append(item0)
  141. elif question.type <= ExamQuestion.MULTIPLE:
  142. rows = ExamQuestionOption.objects.filter(main=question, delete=False)
  143. for row in rows:
  144. option_log = ExamAnswerOptionLog.objects.filter(main=answer_log, option=row).first()
  145. item = {
  146. 'id': row.id,
  147. 'content': row.content,
  148. 'answer': option_log and True or False
  149. }
  150. question_data['option'].append(item)
  151. elif question.type == ExamQuestion.FILL:
  152. rows = ExamQuestionFill.objects.filter(main=question, delete=False)
  153. for row in rows:
  154. option_log = ExamAnswerFillLog.objects.filter(main=answer_log, order=row.order).first()
  155. item = {
  156. 'id': row.order, # 填空题序号
  157. 'content': option_log and option_log.content or '',
  158. }
  159. question_data['option'].append(item)
  160. # 右侧习题类别列表
  161. # 单选、多选、填空。选择答案后,可能会把答案清空,得加上NOTDONE过滤
  162. questions = ExamPaperDetail.objects.filter(main=instance.exampaper, delete=False).values('id','question_id',
  163. )
  164. single_questions_list = []
  165. for single in questions.filter(question__type=ExamQuestion.SINGLE):
  166. answer_log = ExamAnswerLog.objects.filter(main=instance, detail=single['id'])
  167. single_questions_list.append(
  168. {
  169. 'question_id': single['id'],
  170. 'question': single['question_id'],
  171. 'complete': answer_log and True or False,
  172. }
  173. )
  174. # 多选题
  175. multiple_questions_list = []
  176. for multiple in questions.filter(question__type=ExamQuestion.MULTIPLE):
  177. answer_log = ExamAnswerLog.objects.filter(main=instance, detail=multiple['id'])
  178. multiple_questions_list.append(
  179. {
  180. 'question_id': multiple['id'],
  181. 'question': multiple['question_id'],
  182. 'complete': answer_log and True or False,
  183. }
  184. )
  185. # 填空题
  186. fill_questions_list = []
  187. for fill in questions.filter(question__type=ExamQuestion.FILL):
  188. answer_log = ExamAnswerLog.objects.filter(main=instance, detail=fill['id'])
  189. fill_questions_list.append(
  190. {
  191. 'question_id': fill['id'],
  192. 'question': fill['question_id'],
  193. 'complete': answer_log and True or False,
  194. }
  195. )
  196. # 判断题
  197. judgment_questions_list = []
  198. for judgment in questions.filter(question__type=ExamQuestion.JUDGMENT):
  199. answer_log = ExamAnswerLog.objects.filter(main=instance, detail=judgment['id'])
  200. judgment_questions_list.append(
  201. {
  202. 'question_id': judgment['id'],
  203. 'question': judgment['question_id'],
  204. 'complete': answer_log and True or False,
  205. }
  206. )
  207. result = {
  208. 'question_data': question_data, # 下一题练习题
  209. 'single_questions_list': single_questions_list, # 单选
  210. 'multiple_questions_list': multiple_questions_list, # 多选
  211. 'fill_questions_list': fill_questions_list, # 填空
  212. 'judgment_questions_list': judgment_questions_list, # 判断
  213. }
  214. return response_ok(result)
  215. except CustomError as e:
  216. return response_error(e.get_error_msg())
  217. except Exception as e:
  218. traceback.print_exc()
  219. return response_error(str(e))
  220. @action(methods=['post'], detail=True)
  221. def submit_practise(self, request, pk):
  222. # 习题交卷,把上个接口的判断答案,放到此处
  223. try:
  224. instance = self.get_object()
  225. with transaction.atomic():
  226. paper_details = ExamPaperDetail.objects.filter(main=instance.exampaper, delete=False)
  227. for detail in paper_details:
  228. # 创建模拟考试未答题记录,如果没有找到答案记录,则该题保留未答状态
  229. answer_log, create = ExamAnswerLog.objects.get_or_create(main=instance, detail=detail)
  230. # answer_logs = ExamAnswerLog.objects.filter(main=instance)
  231. # for answer_log in answer_logs:
  232. question = detail.question
  233. if question.type == ExamQuestion.SINGLE:
  234. # 单选
  235. answers = ExamAnswerOptionLog.objects.filter(main=answer_log).first()
  236. if answers:
  237. if answers.option.right:
  238. answer_log.status = ExamAnswerLog.RIGHT
  239. instance.single_answer_count += 1
  240. else:
  241. answer_log.status = ExamAnswerLog.WRONG
  242. ErrorBook.add_error(question, request.user, answer_log)
  243. elif question.type == ExamQuestion.MULTIPLE:
  244. # 多选
  245. answers = ExamAnswerOptionLog.objects.filter(main=answer_log).order_by('option_id').values_list(
  246. 'option_id', flat=True)
  247. if answers:
  248. right = ExamQuestionOption.objects.filter(main=question, right=True,
  249. delete=False).values_list('id', flat=True)
  250. if list(answers) == list(right):
  251. answer_log.status = ExamAnswerLog.RIGHT
  252. instance.multiple_answer_count += 1
  253. else:
  254. answer_log.status = ExamAnswerLog.WRONG
  255. ErrorBook.add_error(question, request.user, answer_log)
  256. elif question.type == ExamQuestion.FILL:
  257. # 填空
  258. fill_logs = ExamAnswerFillLog.objects.filter(main=answer_log)
  259. right = True
  260. if fill_logs:
  261. for fill_log in fill_logs:
  262. right_answer = ExamQuestionFill.objects.filter(main=question, content=fill_log.content,
  263. order=fill_log.order, delete=False)
  264. if not right_answer:
  265. right = False
  266. break
  267. if right:
  268. answer_log.status = ExamAnswerLog.RIGHT
  269. instance.fill_answer_count += 1
  270. else:
  271. answer_log.status = ExamAnswerLog.WRONG
  272. ErrorBook.add_error(question, request.user, answer_log)
  273. else:
  274. # 判断
  275. if answer_log.status != ExamAnswerLog.NOTDONE:
  276. if question.judgment == (answer_log.status == ExamAnswerLog.RIGHT):
  277. answer_log.status = ExamAnswerLog.RIGHT
  278. instance.judgment_answer_count += 1
  279. else:
  280. answer_log.status = ExamAnswerLog.WRONG
  281. ErrorBook.add_error(question, request.user, answer_log)
  282. answer_log.save()
  283. instance.submit_time = timezone.now()
  284. use_time = instance.exam_time - instance.submit_time
  285. instance.use_time = use_time.seconds
  286. single_answer_scores = instance.single_answer_count * instance.exampaper.single_scores
  287. multiple_answer_scores = instance.multiple_answer_count * instance.exampaper.multiple_scores
  288. fill_answer_scores = instance.fill_answer_count * instance.exampaper.fill_scores
  289. judgment_answer_scores = instance.judgment_answer_count * instance.exampaper.judgment_scores
  290. instance.single_answer_scores = single_answer_scores
  291. instance.multiple_answer_scores = multiple_answer_scores
  292. instance.fill_answer_scores = fill_answer_scores
  293. instance.judgment_answer_scores = judgment_answer_scores
  294. instance.scores = single_answer_scores + judgment_answer_scores + multiple_answer_scores + fill_answer_scores
  295. # 计算排名
  296. up_rank = ExamLog.objects.filter(exam=instance.exam, scores__gte=instance.scores).count()
  297. instance.rank = up_rank + 1
  298. ExamLog.objects.filter(exam=instance.exam, scores__lte=instance.scores).update(rank=F('rank') + 1)
  299. instance.save()
  300. instance.exampaper.did_count += 1
  301. instance.exampaper.save()
  302. SysLog.objects.addnew(request.user, SysLog.INSERT, u"提交模拟考试题,id=%d" % (instance.id))
  303. except CustomError as e:
  304. return response_error(e.get_error_msg())
  305. except Exception as e:
  306. traceback.print_exc()
  307. return response_error(str(e))
  308. return response_ok()
  309. class ExamQuestionFeedbackViewSet(CustomModelViewSet):
  310. permission_classes = [IsStaff, ]
  311. queryset = ExamQuestionFeedback.objects.filter()
  312. serializer_class = ExamQuestionFeedbackSerializer
  313. def perform_create(self, serializer):
  314. super(ExamQuestionFeedbackViewSet, self).perform_create(serializer)
  315. instance = serializer.instance
  316. validated_data = serializer.validated_data
  317. SysLog.objects.addnew(self.request.user, SysLog.INSERT, u'添加试题错误反馈,id=%d' % instance.id, validated_data)