Files
PORTAL_COD2/src/back/tests/views.py
T

189 lines
7.2 KiB
Python

from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Count
from django.db.models import Q
from .models import *
from userauth.models import *
from .serializers import *
from datetime import datetime
from rest_framework import generics
from navigation.models import News
import json
from collections import defaultdict
import os
from django.conf import settings
from django.urls import reverse
import html
from rest_framework.permissions import IsAuthenticated
import base64
import hashlib
from cryptography.fernet import Fernet
from django.db.models import F
class GetTests(generics.ListAPIView):
queryset = Test.objects.all()
serializer_class = TestsSerializer
def get (self, request, *args, **kwargs):
user = request.user
# user = User.objects.get(username='9966-00-125')
status = request.query_params.get('status')
tests = self.get_tests_by_status(status, datetime.now(), user)
if status != None:
self.set_attemps_number(user, tests)
serialized_tests = self.get_serializer(tests, many=True).data
return Response(serialized_tests)
def get_tests_by_status(self, status, now, user):
print(status)
if status is None:
return Test.objects.all().order_by('dateend')
status_filters = {
'active' : Test.objects.filter(
testing__user=user,
testing__completion_date__gte=now
).distinct(),
'completed' : Test.objects.filter(
testing__user=user,
testing__completion_date__lt=now
).distinct()
}
return status_filters.get(status, Test.objects.none()).order_by('dateend')
def set_attemps_number(self, user, tests):
test_ids = [test.id for test in tests]
attempt_counts = TestAttempt.objects.filter(user=user, test__id__in=test_ids).values('test').annotate(count=Count('test'))
attempt_counts = {item['test']: item['count'] for item in attempt_counts}
for test in tests:
test.attemps_number = test.attemps_number - attempt_counts.get(test.id, 0)
class TestDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Test.objects.all()
serializer_class = TestSerializer
lookup_url_kwarg = 'id'
lookup_field = 'id'
def get(self, request, *args, **kwargs):
test = self.get_object()
number_of_questions = test.question_count
random_questions = test.questions.order_by('?')[:number_of_questions]
test_serialized = TestSerializer(test).data
test_serialized['questions'] = TestQuestionSerializer(random_questions, many=True).data
return Response(test_serialized)
# class TestListCreate(generics.ListCreateAPIView):
# queryset = Test.objects.all()
# serializer_class = TestSerializer
# def get(self, request):
# user = request.user
# now = datetime.now()
# status = request.query_params.get('status')
# tests = self.get_tests_by_status(status, now)
# serialized_tests = TestSerializer(tests, many=True).data
# questions = TestQuestion.objects.filter(test__in=tests)
# questions_by_test_id = defaultdict(list)
# for question in questions:
# questions_by_test_id[question.test.id].append(question)
# for test in serialized_tests:
# test['is_passed'] = self.has_participated(user, test['id'])
# related_questions = questions_by_test_id[test['id']]
# test['files'] = [question.file.url for question in related_questions if question.file]
# return Response(serialized_tests)
# def get_tests_by_status(self, status, now):
# print(status)
# if status is None:
# return Test.objects.all().order_by('dateend')
# status_filters = {
# 'active': Test.objects.filter(dateend__gt=now),
# 'completed': Test.objects.filter(dateend__lt=now),
# }
# return status_filters.get(status, Test.objects.none()).order_by('dateend')
# def has_participated(self, employee, test):
# return TestResult.objects.filter(user=employee, answer__question__test=test).exists()
class GetTesting(APIView):
def get(self, request):
user = request.user
tests = Testing.objects.filter(user=user)
test_names = {test.id: test.test.name for test in tests}
serializer = TestingSeriaizer(tests, many=True).data
for test in serializer:
if test['id'] in test_names:
test['test_name'] = test_names[test['id']]
return Response(serializer)
class TestResultCreate(generics.ListCreateAPIView):
queryset = TestResult.objects.all()
serializer_class = TestResultSerializer
def post(self, request, *args, **kwargs):
user = request.user
# user = User.objects.get(username = "9966-00-125")
test_info = self.get_test_info(request)
test_attempt = self.create_test_attempt(user, test_info)
serializer = self.get_serializer(data=request.data, many=True)
if serializer.is_valid():
serializer.save(attempt=test_attempt)
self.update_testing(user, test_info)
return Response(data={'score': test_info['score'], 'answered_questions_total': test_info['answered_questions_total']})
def create_test_attempt(self, user, test_info):
test = test_info['test']
score = test_info['score']
attempt_count = get_attempt_count(user=user, test=test)+ 1
test_attempt = TestAttempt.objects.create(user=user, test=test , score=score , attempt_number=attempt_count , completion_date= datetime.now())
return test_attempt
def update_testing(self, user, test_info):
test = test_info['test']
test_passed = test_info['is_passed']
Testing.objects.update_or_create(user=user, test=test, defaults = {"completion_date": test.dateend,"test_passed":test_passed})
def get_test_info(self, request):
answer_ids = [item['answer'] for item in request.data]
test_answers = TestAnswer.objects.filter(id__in=answer_ids)
test = test_answers[0].question.test
answered_questions_total = test_answers.values('question').distinct().count()
correct_questions = sum(
TestAnswer.objects.filter(
question=question, id__in=test_answers, right_wrong=True
).count() == TestAnswer.objects.filter(
question=question, right_wrong=True
).count() and TestAnswer.objects.filter(
question=question, id__in=test_answers, right_wrong=False
).count() == 0
for question in set(test_answers.values_list('question', flat=True))
)
pass_perc = test_answers[0].question.test.pass_perc
result = {
"is_passed": correct_questions >= pass_perc,
"score": correct_questions,
"test": test,
"answered_questions_total": answered_questions_total,
}
return result
def get_attempt_count(user, test):
return TestAttempt.objects.filter(user=user, test=test).count()