def post(self, request, format=None): serializer = NameSecretSerializer(data=request.data) if not serializer.is_valid(): return APIResponse(serializer.errors, status=400) name = serializer.data["name"].lower() secret = serializer.data["secret"] authorisation = get_authorisation(name, secret) if authorisation: expired = (Response.objects.filter(name__iexact=name).update( expired_at=timezone.now()) > 0) return APIResponse({ "result": { "authorisation": authorisation.name, "expired": expired } }) return APIResponse( { "result": False, "error": "Invalid authorisation token" }, status=403)
def get(self, request, code=None): if code: try: quiz = Quiz.objects.get(code=code) except ObjectDoesNotExist: return APIResponse(status=status.HTTP_404_NOT_FOUND) serializer = QuizSerializer(quiz) return APIResponse(serializer.data)
def list(self, request): if len(request.query_params) == 0: return super().list(request) else: quiz_id = request.query_params['quizID'] quiz = Quiz.objects.filter(id=int(quiz_id)).first() responses = Response.objects.filter(test=quiz) serializer = ResponseSerializer(responses, many=True) return APIResponse(serializer.data)
def list(self, request): if len(request.query_params) == 0: return super().list(request) else: response_id = request.query_params['responseID'] response = Response.objects.filter(id=int(response_id)).first() answers = self.get_queryset().filter(response=response) serializer = AnswerSerializer(answers, many=True) return APIResponse(serializer.data)
def get(self, request): message, status, data = 'ok', 200, {} try: player = request.query_params.get('player') if not player: raise ValueError('Player param is required') data = dbmanager.recommend_hero(player) except ValueError as err: message = str(err) status = HTTPStatus.HTTP_400_BAD_REQUEST return APIResponse({'message': message, 'data': data}, status=status)
def post(self, request): quiz_id = request.data['quizID'] quiz = Quiz.objects.get(author=request.user, id=quiz_id) print('Quiz is', quiz) questions = Question.objects.filter(test=quiz) for question in questions: print(generate_random_clusters(question)) return APIResponse({"msg": "Ok"})
def post(self, request, format=None): serializer = PublishResponseSerializer(data=request.data) if not serializer.is_valid(): return APIResponse(serializer.errors, status=400) name = serializer.data["name"].lower() response = serializer.data["response"] secret = serializer.data["secret"] authorisation = get_authorisation(name, secret) if authorisation: try: db_response = Response(name=name, response=response, created_by_ip=client_ip(request)) db_response.save() except: return APIResponse( { "result": False, "error": "Could not save response in database" }, status=500, ) else: return APIResponse({ "result": { "authorisation": authorisation.name, "published": True } }) return APIResponse( { "result": False, "error": "Invalid authorisation token" }, status=403)
def get(self, request): message, status, data = 'ok', 200, {} try: players = request.query_params.get('players') if not players: raise ValueError('Players param is required') players = list(csv.reader([players]))[0] drange = request.query_params.get('range') data = dbmanager.compare_players(players, drange) except ValueError as err: message = str(err) status = HTTPStatus.HTTP_400_BAD_REQUEST return APIResponse({'message': message, 'data': data}, status=status)
def external_submit(request): serializer = ExternalSubmitSerializer(data=request.data) serializer.is_valid(raise_exception=True) validated = serializer.validated_data submit = Submit( task=validated['token'].task, user=validated['user'], points=validated['points'], submit_type=constants.SUBMIT_TYPE_EXTERNAL, testing_status=judge_constants.SUBMIT_RESPONSE_OK, ) submit.save() return APIResponse()
def post(self, request): print(f'{request.user} wants to grade') grade_info = request.data['gradeInfo'] response_id = request.data['responseID'] response = Response.objects.get(id=response_id) for answer_id in grade_info.keys(): grade = int(grade_info[answer_id]) answer = Answer.objects.get(id=answer_id) question = Question.objects.get(id=answer.question_id) assert 0 <= grade <= question.maximum_score answer.score = grade answer.save() # MCQs should be graded automatically (already know the correct answer) # get the corresponding quiz quiz = Quiz.objects.get(id=response.test_id) # get all the corresponding answers to response # get all the questions in the quiz questions = Question.objects.filter(test=quiz) answers = Answer.objects.filter(response=response) for question in questions: if question.type == 2: # mcq answer = Answer.objects.get(response=response, question=question) print('got answer', answer) choices = Choice.objects.filter(question=question) for choice in choices: if answer.choice_id == choice.id: if choice.is_answer: print('MCQ is correct') answer.score = question.maximum_score else: answer.score = 0 print('Wrong answer for MCQ') break answer.save() total_score = 0 for answer in answers: total_score += answer.score response.total_score = total_score response.graded = True response.save() return APIResponse({"message": "Successfully graded"}, status=status.HTTP_200_OK)
def post(self, request, format=None): serializer = NameSecretSerializer(data=request.data) if not serializer.is_valid(): return APIResponse(serializer.errors, status=400) name = serializer.data["name"].lower() secret = serializer.data["secret"] authorisation = get_authorisation(name, secret) if authorisation: try: authorisation.reset_secret() authorisation.save() except: return APIResponse( { "result": False, "error": "Could not save authorisation in database", }, status=500, ) else: return APIResponse({ "result": { "authorisation": authorisation.name, "secret": authorisation.secret, } }) return APIResponse( { "result": False, "error": "Invalid authorisation token" }, status=403)
def external_submit(request): """ Receive a request from an external application, create submit with review after validation. """ serializer = ExternalSubmitSerializer(data=request.data) serializer.is_valid(raise_exception=True) validated = serializer.validated_data receiver = SubmitReceiver.objects.get(token=validated['token']) if not receiver.allow_external_submits or not receiver.can_post_submit( validated['user']): raise PermissionDenied() submit = create_submit(user=validated['user'], receiver=receiver) submit.save() review = Review(submit=submit, score=validated['score'], short_response=ReviewResponse.OK) review.save() return APIResponse()
def call_api_hybrid_view_for_api(func, request, *args, **kwargs): response = func(request, *args, **kwargs) if isinstance(response, APIHybridResponse): result = OrderedDict(response.get_api_response(request)) messages = [] for message in get_messages(request): messages.append({ 'level': DEFAULT_MESSAGE_TAGS[message.level], 'message': message.message }) if messages: result['messages'] = messages result.move_to_end('messages', last=False) api_response = APIResponse(result, status=response.status_code) if request.method == 'GET': response.add_headers(api_response) return api_response elif isinstance(response, HttpResponse) and response.status_code in (304, 412): # 304 Not Modified, 412 Precondition Failed return response raise NoAPIHybridResponse
def post(self, request, format=None): return APIResponse(parse(request.data))
def post(self, request, format=None): serializer = NameSecretOptionalSerializer(data=request.data) if not serializer.is_valid(): return APIResponse(serializer.errors, status=400) name = serializer.data["name"].lower() secret = serializer.data.get("secret", "") if settings.ACMEPROXY_AUTHORISATION_CREATION_SECRETS is not None: user = settings.ACMEPROXY_AUTHORISATION_CREATION_SECRETS.get( secret, None) if user is None: return APIResponse( { "result": False, "error": "Invalid account token" }, status=403) else: allowed = True if "permit" in user: allowed = False for permit_name in user["permit"]: if (permit_name.startswith(".") and name.endswith(permit_name)) or ( not permit_name.startswith(".") and permit_name == name): allowed = True break if not allowed: return APIResponse( { "result": False, "error": "Changes to this domain are not permitted with this account token", }, status=403, ) account = user["name"] else: account = "" db_authorisation = Authorisation(name=name, created_by_ip=client_ip(request), account=account) db_authorisation.reset_secret() try: db_authorisation.save() except: return APIResponse( { "result": False, "error": "Could not save authorisation in database" }, status=500, ) return APIResponse({ "result": { "authorisation": db_authorisation.name, "secret": db_authorisation.secret, } })
def list(self, request): queryset = self.get_queryset().filter(author=self.request.user) serializer = QuizSerializer(queryset, many=True) # print(serializer) return APIResponse(serializer.data)
def create(self, request, format=None): emoji = Emoji.objects.get(name=request.data['emoji']) response = Response.objects.create(user=request.user, emoji=emoji) return APIResponse(data=ResponseSerializer(instance=response).data, status=status.HTTP_201_CREATED)
def create(self, request: APIRequest, *args, **kwargs) -> APIResponse: serializer = self.get_serializer(data={"name": self.alias_name()}) serializer.is_valid(raise_exception=True) serializer.save(destination_id=self.destination_id()) return APIResponse(serializer.data, status=status.HTTP_201_CREATED)