Exemple #1
0
 def apply_challenge(self, request):
     try:
         user_id = request.query_params.get("user_id", None)
         completed = request.query_params.get("completed", None)
         id = request.query_params.get("id", None)
         risk = request.query_params.get("risk", None)
         diff_risk = request.query_params.get("diff_risk", None)
         if user_id and completed and id and risk and diff_risk:
             customer = Customer.objects.filter(vk_id=user_id)
             if customer.count() == 1:
                 customer = customer[0]
                 customer.risk = float(risk)
                 challenge = Challenge.objects.get(id=id)
                 answers = challenge.question.answers \
                  .filter(customer__vk_id=user_id).order_by("date")
                 if answers:
                     ans = answers[0]
                     ans.value = True if completed.lower(
                     ) == "true" else False
                     ans.save()
                 else:
                     ans = Answer(customer=customer,
                                  value=True
                                  if completed.lower() == "true" else False,
                                  question=challenge.question)
                     ans.save()
                 customer.diff_risk = float(diff_risk)
                 customer.save()
                 return Response(data={"is": True})
         return Response(data={"is": False})
     except:
         print(traceback.format_exc())
         return Response(data={"is": False})
Exemple #2
0
    def post(self, request, room_number):
        request.session.save()

        if 'room_admin_uuid' not in request.session or request.session['room_admin_uuid'] != room_number:
            return Response({"error": "you can't post polls for this room"}, status=401)
        else:
            room = get_or_none(Room, number=room_number)
            if room:
                json = JSONParser().parse(request)
                poll = Poll(room=room, title=json['title'], isExclusive=json['isExclusive'])
                poll.save()

                for item in json['answers']:
                    answer = Answer(poll=poll, title=item['title'], votes=0)
                    answer.save()

                Group('room-%s' % poll.room.number).send({
                    'text': dumps({
                        'type': 'poll',
                        'action': 'create',
                        'data': PollSerializer(poll).data
                    })
                })

                return Response({}, status=201)

            else:
                return Response({"error": "no room " + room.number + " found"}, status=404)
Exemple #3
0
def PostAnswer(request):
    """!@brief Function for posting an answer which is part of the request body
    @details this function extracts the answer details from the request body, then creates a new entry in the answer table with the corresponding details. It also creates a notification for a user whose question has been provided an answer and increase the field numAnswers for that question by 1
    @post New entries have been created in the answer table as well as the notification table along with an update in th question table to accomodate for the new changes
    @return returns the updated question object
    """
    serializer = AnswerSerializer(data=request.data)
    if serializer.is_valid():
        ans = serializer.validated_data
        sender = ans['user']
        question = ans['question']
        receiver = question.user
        answer = Answer(user=sender,
                        username=sender.name,
                        userdepartment=sender.department,
                        userbio=sender.bio,
                        userdegree=sender.degree,
                        userspecialization=sender.specialization,
                        content=ans['content'],
                        question=question)
        answer.save()
        notification = Notification(receiver=receiver,
                                    sender=sender,
                                    sendername=sender.name,
                                    question=question,
                                    code=3)
        notification.save()
        #print(question.numAnswers)
        question.numAnswers = question.numAnswers + 1
        question.save()
        return QuestionResponse(sender.id, question.id)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #4
0
async def rate_answer(query: types.CallbackQuery):
    callback_data = answer_cb.parse(query.data)

    msg_id = query.message.message_id
    user_id = query.from_user.id
    answer_id = int(callback_data["id"])
    rating = int(callback_data["rating"])
    predictor = callback_data["predictor"]

    logging.info(f"user: {user_id} mark question msg_id: {msg_id} "
                 f"from predictor: {predictor} with rate: {rating}")

    answer = Answer(id_=answer_id,
                    predictor=predictor,
                    rating=rating,
                    msg_id=msg_id)

    try:
        await api_client.update_answer(answer)

    except ApiClientError:
        logging.error(
            f"Got error from api_client.update_answer. Answer={answer}\n"
            f"See the full trace in console.")
        traceback.print_exc()

    text = query.message.text.replace(predictor.replace('\\_', '_'), predictor)
    await bot.edit_message_text(
        text=f"{text}\n\n*ДЯКУЮ ЗА ТЕ, ЩО РОБИШ МЕНЕ КРАЩЕ!*",
        chat_id=query.message.chat.id,
        message_id=query.message.message_id,
        reply_markup=None,
        parse_mode="Markdown")
Exemple #5
0
def add_answer(request, user_id, question_id):

    mentor = Mentor.objects.get(id=user_id)
    question = Question.objects.get(id=question_id)
    answer = Answer()
    answer.author = mentor
    answer.question = question
    answer.title = request.data['title']
    answer.description = request.data['description']
    answer.language = request.data['language']
    answer.save()
    return Response(AnswerSerializer(answer).data,
                    status=status.HTTP_201_CREATED)
Exemple #6
0
    def delete(self, question_id, answer_id):
        answer = Answer.get_or_404(answer_id)
        answer.delete()

        return jsonify({
            "status": "success",
            "message": SUCCESS_MESSAGES["deleted"].format("Answer")
        })
Exemple #7
0
 def test_time_methods(self):
     u = User.objects.create_user(username="******", password="******")
     c = Country.objects.create(gwno=1,
                                name="Somewhere",
                                shape={},
                                simpleshape={},
                                iso2c="SW")
     aw = Answer(date=date(year=1999, month=1, day=1), author=u, country=c)
     self.assertEqual(aw.quarter, 1)
     self.assertEqual(aw.year, 1999)
Exemple #8
0
    def get(self, question_id, answer_id):
        answer = Answer.get_or_404(answer_id)

        answer_schema = AnswerSchema(
            only=["id", "title", "answerer", "children", "parent"])

        return jsonify({
            "data": answer_schema.dump_object_into_schema(answer),
            "status": "success",
            "message": SUCCESS_MESSAGES["fetched"].format("Answers")
        })
Exemple #9
0
    def post(self, question_id):
        request_data = request.get_json()

        user = User.query.get("16")
        question = Question.get_or_404(question_id)

        answer_schema = AnswerSchema(
            only=["id", "title", "created_at", "updated_at", "parent_id"])
        answer_data = answer_schema.load_object_into_schema(request_data)
        answer_data["answerer"] = user
        answer_data["answer"] = question
        answer_data["parent_id"] = 12
        answer = Answer(**answer_data)
        answer.save()

        return jsonify({
            "data": answer_schema.dump_object_into_schema(answer),
            "status": "success",
            "message": SUCCESS_MESSAGES["created"].format("Answer")
        })
Exemple #10
0
    def put(self, question_id, answer_id):
        request_data = request.get_json()

        answer = Answer.get_or_404(answer_id)

        answer_schema = AnswerSchema(only=["title"])
        answer_data = answer_schema.load_object_into_schema(request_data)

        answer = answer.update(answer_data)
        answer.save()

        return jsonify({
            "data": answer_schema.dump_object_into_schema(answer),
            "status": "success",
            "message": SUCCESS_MESSAGES["updated"].format("Answer")
        })
Exemple #11
0
def save_question(question, answer, detractors):
    operator = get_math_operation(question)
    has_negative_values = check_for_negative_values(answer, *detractors)

    q = Question(text=question, operation_type=operator, has_negative_values=has_negative_values)
    q.save()

    all_answers = []
    a = Answer(text=answer, is_correct_answer=True)
    a.save()
    all_answers.append(a)

    for d in detractors:
        a = Answer(text=d, is_correct_answer=False)
        a.save()
        all_answers.append(a)

    q.answers.add(*all_answers)
Exemple #12
0
 async def publish_question(self, query: str, predictor: str, tg_id: int,
                            msg_id: int,
                            chat_id: int) -> Union[Answer, None]:
     resp = await self.fetch(method="/search",
                             params={
                                 "user_id": tg_id,
                                 "query": query,
                                 "predictor": predictor,
                                 "msg_id": msg_id,
                                 "chat_id": chat_id,
                             })
     if resp["success"] is True:
         return Answer(id_=resp["answer"]["id"],
                       text=resp["answer"]["text"],
                       predictor=predictor)
     else:
         return None
Exemple #13
0
 def create_answer(self, question_uuid, classroom_uuid, content):
     success = True
     answer_uuid = uuid.uuid1()
     Answer(
         uuid=answer_uuid,
         question_uuid=question_uuid,
         classroom_uuid=classroom_uuid,
         creator=self.user_id,
         role=self.role,
         anonymous=self.anonymous,
         content=content,
         agree_count=0,
         disagree_count=0,
         created_timestamp=self.timestamp_now,
     ).save()
     try:
         row = Question.objects.get(uuid=question_uuid)
         row.answer_count = F('answer_count') + 1
         row.updated_timestamp = self.timestamp_now
         row.save()
     except Question.DoesNotExist:
         success = False
     return success
Exemple #14
0
def add_answer(questionId):
    """
    Function enables user to add an answer to a question on the platform.
    Checks if there is an empty string and returns a message telling the
    user that they didn't enter anything. Also checks if there are any
    questions in the list and if not returns a message that there are not
    questions yet.
    Then checks if the question whose id they entered exists and if not,
    returns a message that the quetion does not exist else, returns the
    answer the user entered together with the question.

    :param questionId:
    Parameter holds the id of the question that the user wishes to answer.
    """
    data = request.get_json()

    details = data.get('details')

    try:
        if not details or details.isspace():
            return jsonify({'message':
                            'Sorry, you did not enter any answer!'}), 400
        if len(questions) == 0:
            return jsonify({'message':
                            'Sorry, there are no questions yet!!'}), 400

        question = questions[questionId - 1]
        answer = Answer(questionId, details)
        answers.append(answer)

        return jsonify({
            'Question': question.__dict__,
            'Answer': answer.__dict__,
            'Message': 'Answer added succesfully!'
        }), 201
    except IndexError:
        return jsonify({'message': 'Question does not exist.'}), 400
Exemple #15
0
def answer(questionId):
    return Answer.post_answer(questionId)
Exemple #16
0
 def create(self, validated_data):
     answer = Answer(**validated_data)
     answer.author = self.context['request'].user
     answer.save()
     return answer