Exemplo n.º 1
0
 def create_answer(self, question_id, text, is_correct):
     """create a new answer and add it to the store and to the quiz"""
     new_answers = Answer(question_id, text, is_correct)
     self.get_question_by_id(question_id).add_answer_by_id(
         new_answers.answer_id)
     self.answers[new_answers.answer_id] = new_answers
     return new_answers.answer_id
Exemplo n.º 2
0
 def get_answers(self):
     query = Answer.all()
     cookies = h.get_default_cookies(self)
     current_user = h.get_current_user(cookies)
     query.filter("user =", current_user)
     answers = query.fetch(1000)
     return answers
Exemplo n.º 3
0
def addQuestion(qId: str, answer: Answer):
    answer.aId = str(uuid.uuid1())
    data = answer.__dict__
    data["author"] = answer.author.__dict__
    for question in qaDb["questions"]:
        if question["qId"] == qId:
            question["answerList"].append(data)
    with open('qaDb.json', 'w') as f:
        f.write(json.dumps(qaDb, indent=4, sort_keys=True))
    return True
Exemplo n.º 4
0
def createAnswer(questionId, accountId, answer, pollStatus):
    answ = Answer()

    answ.QuestionId = questionId
    answ.AccountId = accountId
    account = Account.query.filter_by(Id=accountId).first()
    account.setDomainExpertise()
    if len(account.DomainExpertise) > 0:
        answ.IsExpert = True
    else:
        answ.IsExpert = False
    answ.Answer = answer
    answ.TimeStamp = datetime.date.today()
    answ.Score = 0
    poll = PollOption.query.filter_by(PollOptionName=pollStatus).first()
    answ.PollOptionId = poll.Id
    db.session.add(answ)
    db.session.commit()

    return answ
Exemplo n.º 5
0
 def post(self):
     args = parser.parse_args()
     d = {
         'title': args['title'],
         'content': args['content'],
         'user_id': args['user_id'],
         'question_id': args['question_id']
     }
     a = Answer.new(d)
     a.save()
     return a.json(), 201
Exemplo n.º 6
0
    def put(self):
        payload = request.get_json(force=True)

        if payload is None:
            payload = {}

        new_answer = Answer(text=payload.get('answer'))

        db.session.add(new_answer)
        db.session.commit()

        return {'message': 'Successfully added'}, 200
Exemplo n.º 7
0
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('device_id',
                            required=True,
                            type=str,
                            help='Device ID missing in query parameter')
        device_id = parser.parse_args().get('device_id')

        results = Answer.find_by_device_id(device_id)
        if results:
            return_list = [{
                'session_id':
                session,
                'answer_ids': [
                    i.answer_id for i in Answer.find_by_session_and_device_id(
                        session, device_id)
                ],
                'session_start_time':
                min([
                    i.answered_time
                    for i in Answer.find_by_session_and_device_id(
                        session, device_id)
                ]),
                'session_end_time':
                max([
                    i.answered_time
                    for i in Answer.find_by_session_and_device_id(
                        session, device_id)
                ])
            } for session in list(
                set([result.session_id for result in results]))]

            return {'results': return_list}, 200

        else:
            return {
                'message':
                'no sessions found for device_id {}'.format(device_id)
            }, 404
Exemplo n.º 8
0
 def add_answer(self, atext, qkey):
     answer = Answer()
     cookies = h.get_default_cookies(self)
     current_user = h.get_current_user(cookies)
     if current_user:
         answer.user = current_user
     answer.atext = atext
     answer.qkey = db.Key(qkey)
     answer.put()
     return answer
Exemplo n.º 9
0
 def delete(self, question_id):
     Answer.delete(id=int(question_id))
     return '', 204
Exemplo n.º 10
0
 def get(self, question_id):
     a = Answer.find_by(id=int(question_id))
     abort_if_answer_doesnt_exist(a)
     return a.json()
Exemplo n.º 11
0
        id=1,
        name="Conseil d'administration",
        description=
        "Vote de confiance pour les postes saisonniers au conseil d'administration de l'AGEG."
    )
    groups = [groupe_exec, groupe_admin]

    questions = generer_questions_exec(groupe_exec.gid)
    question_admin = Question(
        id=100,
        code="CASA19",
        gid=groupe_admin.gid,
        title="Qui voulez-vous comme administrateurs saisonniers de l'AGEG?",
        type='F')
    question_admin.add_answer(
        Answer(qid=question_admin.qid, value="Oui", code="A1", order=1))
    question_admin.add_answer(
        Answer(qid=question_admin.qid, value="Non", code="A2", order=2))

    sousquestions_admin = generer_sousquestion_admin(question_admin)
    options_admin = generer_options_admin()

    for option in options_admin:
        question_admin.add_option(option)

    questions.append(question_admin)
    mylookup = TemplateLookup(directories=['.'],
                              input_encoding="utf-8",
                              output_encoding="utf-8")
    mytemplate = Template(filename='templates/base.mako',
                          lookup=mylookup,
Exemplo n.º 12
0
def showQuestion(question_id, methods=['GET', 'POST']):
    # Shows the respective question related to the current survey (latest active one).
    # If there already is a feedback id stored in cookie, the controller's action retrieves it and
    #   fills the form/question if there was already an answer to that question.
    # The page has links to next and previous question.
    # Renders a different view based on the question type.

    # Get feedback object
    cookie = request.cookies['feedback_id']
    feedback = session.query(Feedback).filter_by(id_=int(cookie)).one()

    # Form dict - can this be factored out of each function?
    qtype_forms = {
        'Freeform': AnswerFormFree(request.form),  # can this be removed?
        'Text': AnswerFormFree(request.form),
        'Thumbs': AnswerFormThumbs(request.form),
        'Stars': AnswerFormStars(request.form),
        'Smileys': AnswerFormSmileys(request.form),
        'Choices': AnswerFormChoices(request.form),
        'Picture': AnswerFormFree(request.form)
    }

    progress = 0

    # GET: Show question with prefilled answer
    if request.method == 'GET':
        # Get list of survey questions
        q = session.query(Question).filter_by(id_=question_id).one()
        q_list = session.query(Question).filter_by(
            survey_id_=q.survey_id_).all()
        q_list_ids = [question.id_ for question in q_list]

        # Figure out next_url and prev_url
        prev_q_ix = q_list_ids.index(
            q.id_) - 1 if q_list_ids.index(q.id_) - 1 >= 0 else None
        next_q_ix = q_list_ids.index(
            q.id_) + 1 if q_list_ids.index(q.id_) + 1 < len(q_list) else None
        prev_url = url_for('controllers.showQuestion',
                           question_id=q_list_ids[prev_q_ix]
                           ) if prev_q_ix != None else None  # <---
        next_url = url_for(
            'controllers.showQuestion', question_id=q_list_ids[next_q_ix]
        ) if next_q_ix != None else url_for('controllers.thankYou')
        is_first = prev_url == None

        # Set up proper template and form_action_url
        template = templates.get(
            q.type_, 'freeform.html')  # Freeform is default fallback
        form_action_url = '/feedback/questions/' + str(q.id_)

        # Set up question form and fetch possible pre-existing answer
        form = qtype_forms.get(q.type_, AnswerFormFree(request.form))

        # Check for pre-existing answers
        try:
            pre_existing_answer = session.query(Answer).filter_by(
                question_id_=q.id_,
                feedback_id_=request.cookies['feedback_id']).order_by(
                    Answer.created_at_.desc()).first()
        except:
            pre_existing_answer = None

        if pre_existing_answer != None:
            # Parse answer in db to response parameters for displaying it
            form.value_.data = pre_existing_answer.value_

        if q.type_ == 'Choices':
            form.setChoices(q.questionchoices)

        # Get progress
        progress, missing = get_progress(feedback)

        response = make_response(
            render_template(template,
                            form=form,
                            form_action_url=form_action_url,
                            question_id=q.id_,
                            question_title=q.title_,
                            question_type=q.type_,
                            prev_url=prev_url,
                            next_url=next_url,
                            is_first=is_first,
                            progress=progress,
                            answer=pre_existing_answer))

        return response

    # POST: Write answer to database
    elif request.method == 'POST':
        # Get question type
        question = session.query(Question).filter_by(
            id_=request.form['question_id']).first()

        # Parse new answer from form if it exists
        if request.form.get('value_'):
            new_answer_val = str(request.form['value_'])

        # If mandatory question is missing answer
        elif bool(question.optional_) == False:
            flash('Please answer this question.')
            this_url = url_for('controllers.showQuestion',
                               question_id=question.id_)
            return redirect(this_url)

        # If optional question is missing answer, create empty answer value
        else:
            new_answer_val = ''

        # Get possible pre-existing answer
        answers = session.query(Answer).filter_by(
            feedback_id_=int(request.cookies['feedback_id']),
            question_id_=int(request.form['question_id'])).all()

        # If pre-existing answer found, take the answer object for updating
        if len(answers) > 0:
            answer_object = answers[0]
        # If no pre-existing answer found
        else:
            # Add placeholder '' to value_
            answer_object = Answer('', int(request.cookies['feedback_id']),
                                   int(request.form['question_id']))

        # Special question type (Picture)
        if question.type_ == 'Picture':
            # user gave a new file:
            if request.files.get('userPicture'):
                file = request.files['userPicture']
                if file:
                    fileName = 'F' + str(answer_object.feedback_id_) + 'A' + str(question.id_) + \
                                '_' + str(datetime.datetime.now().hour) + \
                                '_' + str(datetime.datetime.now().minute) + \
                                '_' + str(datetime.datetime.now().second) + '.PNG'
                    imgPath = '/static/' + fileName
                    file.save(parentdir + imgPath)
                    answer_object.image_source_ = imgPath
                    answer_object.value_ = imgPath
                    session.add(answer_object)
                    session.commit()
        # All other question types:
        else:
            answer_object.value_ = new_answer_val

        session.add(answer_object)
        session.commit()

        #----------------------------------------------------------------------
        # NOTE: Replacing value_ with '' will only removes path to img, img data has to be removed separately
        #----------------------------------------------------------------------

        # Redirect to previous if 'Prev' was clicked
        if 'Previous' in request.form.keys():
            return redirect(request.form['prev_url'])

        # Redirect to next if 'Next' was clicked
        if 'Next' in request.form.keys():
            return redirect(request.form['next_url'])

        return 'POST redirection to next/prev failed'
def showQuestion(question_id, methods=['GET', 'POST']):
    # Shows the respective question related to the current survey (latest active one).
    # If there already is a feedback id stored in cookie, the controller's action retrieves it and
    #   fills the form/question if there was already an answer to that question.
    # The page has links to next and previous question.
    # Renders a different view based on the question type.

    print('\n--- ENTERING showQuestion WITH METHOD {}: {}'.format(
        request.method, 70 * '*'))

    # Get feedback object
    cookie = request.cookies['feedback_id']
    feedback = session.query(Feedback).filter_by(id_=int(cookie)).one()
    print('\n--- COOKIE / SESSION ID: {}'.format(cookie))
    print('---FEEDBACK: {}'.format(feedback.serialize))

    # Form dict - can this be factored out of each function?
    qtype_forms = {
        'Freeform': AnswerFormFree(request.form),  # can this be removed?
        'Text': AnswerFormFree(request.form),
        'Thumbs': AnswerFormThumbs(request.form),
        'Stars': AnswerFormStars(request.form),
        'Smileys': AnswerFormSmileys(request.form),
        'Choices': AnswerFormChoices(request.form),
        'Picture': AnswerFormFree(request.form)
    }

    progress = 0

    # GET: Show question with prefilled answer
    if request.method == 'GET':
        print('GET')
        print('request.form: {}'.format(request.form))

        # Get list of survey questions
        q = session.query(Question).filter_by(id_=question_id).one()
        q_list = session.query(Question).filter_by(
            survey_id_=q.survey_id_).all()
        q_list_ids = [question.id_ for question in q_list]

        # Figure out next_url and prev_url
        prev_q_ix = q_list_ids.index(
            q.id_) - 1 if q_list_ids.index(q.id_) - 1 >= 0 else None
        next_q_ix = q_list_ids.index(
            q.id_) + 1 if q_list_ids.index(q.id_) + 1 < len(q_list) else None
        prev_url = url_for('controllers.showQuestion',
                           question_id=q_list_ids[prev_q_ix]
                           ) if prev_q_ix != None else None  # <---
        next_url = url_for(
            'controllers.showQuestion', question_id=q_list_ids[next_q_ix]
        ) if next_q_ix != None else url_for('controllers.thankYou')
        is_first = prev_url == None

        # Set up proper template and form_action_url
        template = templates.get(
            q.type_, 'freeform.html')  # Freeform is default fallback
        print('Chose template {} from templates: {}'.format(
            template, templates))
        form_action_url = '/feedback/questions/' + str(q.id_)

        # Set up question form and fetch possible pre-existing answer
        form = qtype_forms.get(q.type_, AnswerFormFree(request.form))
        print('Chose form {} from qtype_forms'.format(form))
        print('---FORM.value_: {}'.format(form.value_))
        print('---FORM.value_.data: {}'.format(form.value_.data))
        # flash('Feedback_id == Cookie == {}'.format(feedback.id_))
        # flash('form.value_.data: {}'.format(form.value_.data))

        # Check for pre-existing answers
        try:
            print('---CHECK FOR PRE-EXISTING ANSWER:')
            pre_existing_answer = session.query(Answer).filter_by(
                question_id_=q.id_,
                feedback_id_=request.cookies['feedback_id']).order_by(
                    Answer.created_at_.desc()).first()
            print('---FOUND PRE-EXISTING ANSWER:', pre_existing_answer)
        except:
            pre_existing_answer = None

        if pre_existing_answer != None:
            print('---PRE-EXISTING ANSWER FOUND WITH VALUE {}'.format(
                pre_existing_answer.value_))

            # Parse answer in db to response parameters for displaying it
            print('--- CREATING RESPONSE PARAMS FROM PRE-EXISTING ANSWER:')
            print(
                '--- PRE-EXISTING ANSWER: {}, QTYPE: {}, FORM.VALUE_.DATA: {}'.
                format(pre_existing_answer.value_, q.type_, form.value_.data))
            form.value_.data = pre_existing_answer.value_
            print('form.value_.data is now {} "{}"'.format(
                type(form.value_.data), form.value_.data))
        else:
            print('---NO PRE-EXISTING ANSWER FOUND.')

        if q.type_ == 'Choices':
            form.setChoices(q.questionchoices)

        # Debug statements
        print('---TEMPLATE: {}, {}'.format(type(template), template))
        print('---FORM: {}, {}'.format(type(form), form))
        print('---FORM.VALUE_: {}'.format(form.value_))
        print('---FORM.VALUE_.DATA: {}'.format(form.value_.data))
        print('---FORM_ACTION_URL: {}, {}'.format(type(form_action_url),
                                                  form_action_url))
        print('---LIST OF QUESTION IDS: {}'.format(q_list_ids))
        print('---QUESTION: {}, {}'.format(type(q), q))
        print('---QUESTION TYPE: {}, {}'.format(type(q.type_), q.type_))
        print('---IS_FIRST: {}, {}'.format(type(is_first), is_first))
        print('---QUESTION_ID: {}, {}'.format(type(q.id_), q.id_))
        print('---QUESTION_TITLE: {}, {}'.format(type(q.title_), q.title_))
        print('---NEXT_URL: {}, {}'.format(type(next_url), next_url))
        print('---PREV_URL: {}, {}'.format(type(prev_url), prev_url))

        # Get progress
        progress, missing = get_progress(feedback)

        # print('---PROGRESS {}'.format(progress))
        # print('---MISSING {}'.format(missing))
        # print('---MISSING MANDATORY {}'.format(missing))
        # flash('progress: {}'.format(progress))
        # flash('missing: {}'.format(missing))
        # flash('missing: {}'.format(missing))

        #
        #--------- DEBUG HERE Thumbs form!!!
        # form = qtype_forms.get('Thumb', AnswerFormFree(request.form))
        print('form.value_: "{}"'.format(form.value_))
        print('form.value_.data: "{}"'.format(form.value_.data))
        if q.type_ not in ['Freeform', 'Text', 'Picture', 'Thankyou']:
            print('form.value_.choices: "{}"'.format(form.value_.choices))

        print('---FORM: {}'.format(form))
        print('---FORM.VALUE_.DATA: {}'.format(form.value_.data))

        response = make_response(
            render_template(template,
                            form=form,
                            form_action_url=form_action_url,
                            question_id=q.id_,
                            question_title=q.title_,
                            question_type=q.type_,
                            prev_url=prev_url,
                            next_url=next_url,
                            is_first=is_first,
                            progress=progress,
                            answer=pre_existing_answer))

        print('---RESPONSE CREATED. EXITING showQuestion AND RENDERING {}'.
              format(template))

        return response

    # POST: Write answer to database
    elif request.method == 'POST':
        print('POST')
        print('request.form: {}'.format(request.form))
        print('request.cookies: {}'.format(request.cookies))

        # Get question type
        question = session.query(Question).filter_by(
            id_=request.form['question_id']).first()

        # Parse new answer from form if it exists
        if request.form.get('value_'):
            new_answer_val = str(request.form['value_'])

        # If mandatory question is missing answer
        elif bool(question.optional_) == False:
            print('---THIS QUESTION ({}) IS MANDATORY!'.format(question.id_))
            flash('Please answer this question.')
            this_url = url_for('controllers.showQuestion',
                               question_id=question.id_)
            return redirect(this_url)

        # If optional question is missing answer, create empty answer value
        else:
            new_answer_val = ''
        print('---GOT new_answer_val FROM FORM: {}'.format(new_answer_val))

        # Get possible pre-existing answer
        print('---GET POSSIBLE PRE-EXISTING ANSWER')
        answers = session.query(Answer).filter_by(
            feedback_id_=int(request.cookies['feedback_id']),
            question_id_=int(request.form['question_id'])).all()
        print('len(answer_object): {}'.format(len(answers)))

        # If pre-existing answer found, take the answer object for updating
        if len(answers) > 0:
            answer_object = answers[0]
            print('---FOUND PRE-EXISTING ANSWER: {}'.format(answer_object))
            print('---PRE-EXISTING answer.value_: {}'.format(
                answer_object.value_))
        # If no pre-existing answer found
        else:
            print('---NO PRE-EXISTING ANSWER FOUND!')
            # Add placeholder '' to value_
            answer_object = Answer('', int(request.cookies['feedback_id']),
                                   int(request.form['question_id']))
            print('---CREATED NEW ANSWER OBJECT:')

        # Special question type (Picture)
        if question.type_ == 'Picture':
            # user gave a new file:
            if request.files.get('userPicture'):
                file = request.files['userPicture']
                if file:
                    fileName = 'F' + str(answer_object.feedback_id_) + 'A' + str(question.id_) + \
                                '_' + str(datetime.datetime.now().hour) + \
                                '_' + str(datetime.datetime.now().minute) + \
                                '_' + str(datetime.datetime.now().second) + '.PNG'
                    imgPath = '/static/' + fileName
                    file.save(parentdir + imgPath)
                    answer_object.image_source_ = imgPath
                    answer_object.value_ = imgPath
                    session.add(answer_object)
                    session.commit()
        # All other question types:
        else:
            answer_object.value_ = new_answer_val

        print('answer.serialize {}'.format(answer_object.serialize))
        print('---ANSWER_OBJECT.value_ type: {}, len {} value_ {}'.format(
            type(answer_object.value_),
            len(answer_object.value_),
            answer_object.value_,
        ))

        session.add(answer_object)
        session.commit()

        #----------------------------------------------------------------------
        # TODO: Maybe allow for zero length answer if user wants to remove answer?
        # NOTE: Replacing value_ with '' will only removes path to img, img data has to be removed separately
        #----------------------------------------------------------------------

        # Redirect to previous if 'Prev' was clicked
        if 'Previous' in request.form.keys():
            print('---EXITING showQuestion [POST], REDIRECTING TO PREV: {}'.
                  format(request.form['prev_url']))
            return redirect(request.form['prev_url'])

        # Redirect to next if 'Next' was clicked
        if 'Next' in request.form.keys():
            print('---EXITING showQuestion [POST], REDIRECTING TO NEXT: {}'.
                  format(request.form['next_url']))
            return redirect(request.form['next_url'])

        return 'POST redirection to next/prev failed'
Exemplo n.º 14
0
q4 = Question(type_='Smileys',
              title_="Q2: Air quality",
              survey_id_=1,
              optional_=True)
q4_c1 = QuestionChoice(title_="frown", question_id_=3)
q4_c2 = QuestionChoice(title_="meh", question_id_=3)
q4_c3 = QuestionChoice(title_="incredible", question_id_=3)

# Feedbacks
fb_1 = Feedback(survey_id_=1)
fb_2 = Feedback(survey_id_=1)
fb_3 = Feedback(survey_id_=1)
fb_4 = Feedback(survey_id_=1)

# Answers from first feedback (survey was 1)
a_f1_q1 = Answer(value_=q1_c1.title_, feedback_id_=1, question_id_=1)
a_f1_q2 = Answer(value_='Wow, I feel fabulous, thank you!',
                 feedback_id_=1,
                 question_id_=2)

# Answers from second feedback (survey was 1)
a_f2_q1 = Answer(value_=q1_c2.title_, feedback_id_=2, question_id_=1)
a_f2_q2 = Answer(value_='I feel miserable. The bus ride ruined my day.',
                 feedback_id_=2,
                 question_id_=2)

# Answers from third feedback (survey was 2)
a_f3_q3 = Answer(value_=q3_c4.title_, feedback_id_=3, question_id_=3)
a_f3_q4 = Answer(value_=q4_c1.title_, feedback_id_=3, question_id_=4)

# Answers from fourth feedback (survey was 2)
Exemplo n.º 15
0
    def interact(self, msg, token, user):
        result = self.luis.message(msg)

        self.db.add_message(
            token,
            Answer('my_message',
                   msg,
                   user=user,
                   createdAt=datetime.now().strftime('%H:%M')))

        try:
            if result.score >= 0.5:
                if result.intent == 'Travel.Flight':
                    if len(result.entities) == 0:
                        res = self.data.get_flights('Moscow')
                        res = self.magic_sorted(res)
                        self.save_flight(token, res,
                                         Iata().get_city_name(res.destination))

                        self.db.set_places(token, [])
                        self.db.set_hotel(token, None)

                        return Answer('flights_from', data=res)
                    else:
                        res = self.data.get_flights(
                            'Moscow', dest=result.entities[0].entity)
                        res = self.magic_sorted(res)
                        self.save_flight(token, res, result.entities[0].entity)

                        self.db.set_places(token, [])
                        self.db.set_hotel(token, None)

                        return Answer('flights_to', data=res)

                elif result.intent == 'Travel.Hotel':
                    topic = self.db.get_topic(token)
                    if topic.destination:
                        res = self.data.get_hotels(topic.destination)
                        if result.entities[0].entity in self.poi:
                            res = self.poi_sorted(res,
                                                  result.entities[0].entity)
                        else:
                            res = self.magic_sorted(res)

                        topic = self.db.get_topic(token)
                        topic.topic = 'hotel_found'
                        self.db.set_topic(token, topic)
                        self.db.set_hotel(token, res)

                        return Answer('hotel', data=res)
                    else:
                        return Answer('no_topic')
                elif result.intent == 'Travel.Places':
                    topic = self.db.get_topic(token)
                    if topic.destination:
                        res = self.data.get_places(topic.destination)[:5]

                        topic = self.db.get_topic(token)
                        topic.topic = 'places_found'
                        self.db.set_topic(token, topic)
                        self.db.set_places(token, res)

                        return Answer('places', data=res)
                    else:
                        return Answer('no_topic')
                elif result.intent == 'Travel.Price':
                    topic = self.db.get_topic(token)
                    if topic.topic == 'flight_found':
                        res = self.data.get_flights(topic.origin,
                                                    dest=topic.destination)
                        res.sort(key=lambda p: p.price)
                        self.save_flight(
                            token, res[0],
                            Iata().get_city_name(res[0].destination))
                        return Answer('flights_to', data=res[0])
                    elif topic.topic == 'hotel_found':
                        res = self.data.get_hotels(topic.destination)
                        res.sort(key=lambda p: p.price)
                        self.db.set_hotel(token, res[0])
                        return Answer('hotel', data=res[0])
                    else:
                        return Answer('not_understand')
                elif result.intent == 'Travel.Food':
                    topic = self.db.get_topic(token)
                    if topic.destination:
                        res = self.data.get_food(topic.destination)[:1]

                        topic = self.db.get_topic(token)
                        topic.topic = 'food_found'
                        self.db.set_topic(token, topic)
                        self.db.set_food(token, res)

                        return Answer('food', data=res)
                    else:
                        return Answer('no_topic')
                else:
                    return Answer('not_understand')
            else:
                return Answer('not_understand')
        except Exception as e:
            print(e)
            return Answer('not_understand')