views.py 19 KB

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