views.py 17 KB

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