コード例 #1
0
def editQuestion(survey_id, question_id):
    form = QuestionForm(request.form)
    questionToBeEdited = session.query(Question).filter(
        Question.id_ == question_id, Question.survey_id_ == survey_id).one()

    if request.method == 'GET':
        # pre-filling the form:
        form.type_.data = questionToBeEdited.type_
        form.title_.data = questionToBeEdited.title_
        form.optional_.data = questionToBeEdited.optional_

        return render_template('edit_question.html',
                               form=form,
                               survey_id=survey_id,
                               question_id=question_id)
    elif (request.method == 'POST') and (form.validate()):
        # editing the question:
        questionToBeEdited.type_ = form.type_.data
        questionToBeEdited.title_ = form.title_.data
        questionToBeEdited.optional_ = form.optional_.data

        session.add(questionToBeEdited)
        session.commit()
        return redirect("/surveys/" + str(survey_id) + "/questions")
    else:
        return render_template('edit_question.html',
                               form=form,
                               survey_id=survey_id,
                               question_id=question_id)
コード例 #2
0
def editSurvey(id):
    form = SurveyForm(request.form)
    surveyToBeEdited = session.query(Survey).filter_by(id_=id).one()

    if request.method == 'GET':
      # the query returns the survey:

      form.name.data = surveyToBeEdited.name_
      form.description.data = surveyToBeEdited.description_
      form.start_date.data = surveyToBeEdited.start_date_
      form.end_date.data = surveyToBeEdited.end_date_
      form.enabled.data = surveyToBeEdited.enabled_

      return render_template('edit_survey.html', form=form)
    if (request.method == 'POST'):
      if (form.validate()):
        if form.start_date.data <= form.end_date.data:
          surveyToBeEdited.name_ = form.name.data
          surveyToBeEdited.description_ = form.description.data
          surveyToBeEdited.start_date_ = form.start_date.data
          surveyToBeEdited.end_date_ = form.end_date.data
          surveyToBeEdited.enabled_ = form.enabled.data
          session.add(surveyToBeEdited) # this updates the database
          session.commit()
          return redirect('/surveys')
        else:
          flash("Survey creation error: start_date is after end_date.")
          return render_template('edit_survey.html', form=form)
      else:
        return render_template('edit_survey.html', form=form)
コード例 #3
0
ファイル: Feedbacks.py プロジェクト: Arvinje/pts_feedback
def get_progress(feedback, verbose=False):
    survey_id = feedback.survey_id_
    questions = session.query(Question).filter_by(survey_id_=survey_id).all()
    answers = session.query(Answer).filter_by(feedback_id_=feedback.id_).all()
    question_ids = set([item.id_ for item in questions])
    optional_question_ids = set(
        [item.id_ for item in questions if bool(item.optional_) == True])
    answered_ids = set([item.question_id_ for item in answers])

    # Proportion of valid answer ids vs questions
    progress = int(len(answered_ids) / float(len(question_ids)) *
                   100) if len(question_ids) > 0 else 0.0

    # Ids of missing mandatory questions
    missing = list(question_ids.difference(answered_ids))

    return progress, missing
コード例 #4
0
def deleteQuestion(survey_id, question_id):
    form = QuestionForm(request.form)
    questionToBeDeleted = session.query(Question).filter(
        Question.id_ == question_id, Question.survey_id_ == survey_id).one()

    if request.method == 'GET':
        return render_template('delete_question.html',
                               type_=questionToBeDeleted.type_,
                               title_=questionToBeDeleted.title_)
    elif (request.method == 'POST'):
        # deleting all the questionChoices of question:
        for questionChoiceToBeDeleted in session.query(
                QuestionChoice).filter_by(question_id_=question_id).all():
            session.delete(questionChoiceToBeDeleted)
        session.delete(questionToBeDeleted)
        session.commit()
        return redirect("/surveys/" + str(survey_id) + "/questions")
    else:
        return render_template('delete_question.html', form=form)
コード例 #5
0
def deleteSurvey(id):
    surveyToBeDeleted = session.query(Survey).filter_by(id_=id).one()

    if request.method == 'GET':
      return render_template('delete_survey.html', id_=surveyToBeDeleted.id_, name=surveyToBeDeleted.name_)
    elif (request.method == 'POST'):
      if (startDateIsBeforeToday(surveyToBeDeleted.start_date_)):
        # deleting all the questions of survey:
        for questionToBeDeleted in session.query(Question).filter_by(survey_id_=id).all():
          session.delete(questionToBeDeleted)

        session.delete(surveyToBeDeleted)
        session.commit()

        return redirect('/surveys')
      else:
        flash("Survey deletion error: start_date is not in the future.")
        return render_template('delete_survey.html', id_=surveyToBeDeleted.id_, name=surveyToBeDeleted.name_)
    else:
      return render_template('delete_survey.html', id_=surveyToBeDeleted.id_, name=surveyToBeDeleted.name_)
コード例 #6
0
def deleteQuestionChoice(survey_id,question_id,questionChoice_id):
	questionChoiceToBeDeleted = session.query(QuestionChoice).filter(QuestionChoice.id_==questionChoice_id,\
				QuestionChoice.question_id_==question_id).one()

	if request.method == 'GET':
		return render_template('delete_questionchoice.html', title=questionChoiceToBeDeleted.title_,\
			survey_id=survey_id,question_id=question_id)
	elif (request.method == 'POST'):
		session.delete(questionChoiceToBeDeleted)
		session.commit()
		return redirect("/surveys/" + str(survey_id) + "/questions")
コード例 #7
0
def exportSurveyResultsToCSVFile(survey_id):
    si = io.StringIO()
    outputWriter = csv.writer(si)

    #printing question titles as a header:
    questions = session.query(Question).order_by(
        Question.id_).filter(Question.survey_id_ == survey_id).all()
    questionIDs = ["feedback_id"]
    for question in questions:
        questionIDs.append(question.title_)
    outputWriter.writerow(questionIDs)
    outputWriter.writerow("")

    #searching for all the feedback of survey:
    feedbacks = session.query(Feedback).filter(
        Feedback.survey_id_ == survey_id).all()
    for feedback in feedbacks:
        answers = [str(feedback.id_)]
        #searching an answer for each question:
        for question in questions:
            answer = session.query(Answer).filter(
                Answer.feedback_id_ == feedback.id_,
                Answer.question_id_ == question.id_).first()

            # if no answer is given, empty value is printed
            if answer == None:
                answers.append("empty")
            else:
                answers.append(answer.value_)

        outputWriter.writerow(answers)

    #exporting file:
    output = make_response(si.getvalue())
    output.headers[
        "Content-Disposition"] = "attachment; filename=feedback_export.csv"
    output.headers["Content-type"] = "text/csv"

    return output
コード例 #8
0
ファイル: Feedbacks.py プロジェクト: PetNamedEr/pts_feedback
def get_progress(feedback, verbose=False):
    survey_id = feedback.survey_id_
    questions = session.query(Question).filter_by(survey_id_=survey_id).all()
    answers = session.query(Answer).filter_by(feedback_id_=feedback.id_).all()
    missing_q_ids = set([item.id_ for item in questions])
    missing_a_ids = set(
        [item.question_id_ for item in answers if len(item.value_) > 0])
    missing = missing_q_ids.difference(missing_a_ids)
    progress = int(len(missing_a_ids) / float(len(missing_q_ids)) * 100)

    missing_mandatory = []
    for item in questions:
        if verbose:
            print(item.id_, item.title_)
            print('OPTIONAL: {}'.format(item.optional_))
            print('IN MISSING: {}'.format(item.id_ in missing))
        if not bool(item.optional_) and item.id_ in missing:
            print('---MISSING MANDATORY QUESTION WITH ID {}: {}'.format(
                item.id_, item.title_))
            missing_mandatory.append(item.title_)

    return progress, missing, missing_mandatory
コード例 #9
0
def questionChoices(survey_id,question_id):
	form = QuestionChoiceForm(request.form)
	if (request.method == 'GET'):
		return render_template('questionChoices.html',survey_id=survey_id,question_id=question_id,
			questionChoices=session.query(QuestionChoice).order_by(QuestionChoice.id_).filter\
							(QuestionChoice.question_id_ == question_id).all())

	if (request.method == 'POST') and (form.validate()):
		newQuestionChoice = QuestionChoice(form.title_.data, question_id)
		session.add(newQuestionChoice)
		session.commit()
		return redirect("/surveys/" + str(survey_id) + "/questions")
	else:
		return render_template('new_questionchoice.html', form=form,survey_id=survey_id,question_id=question_id)
コード例 #10
0
def get_progress(feedback, verbose=False):
    survey_id = feedback.survey_id_
    questions = session.query(Question).filter_by(survey_id_=survey_id).all()
    answers = session.query(Answer).filter_by(feedback_id_=feedback.id_).all()
    question_ids = set([item.id_ for item in questions])
    optional_question_ids = set(
        [item.id_ for item in questions if bool(item.optional_) == True])
    answered_ids = set([item.question_id_ for item in answers])

    # Proportion of valid answer ids vs questions
    progress = int(len(answered_ids) / float(len(question_ids)) *
                   100) if len(question_ids) > 0 else 0.0

    # Ids of missing mandatory questions
    missing = list(question_ids.difference(answered_ids))

    # Debug statements
    print('---LIST OF ALL QUESTIONS: {}'.format(question_ids))
    print('---LIST OF OPTIONAL QUESTIONS: {}'.format(optional_question_ids))
    print('---GET PROGRESS: ANSWERED IDS ARE: {}'.format(answered_ids))
    print('---PROGRESS IS {}'.format(progress))
    print('---MISSING MANDATORY QUESTIONS IN TOTAL: {}'.format(missing))

    return progress, missing
コード例 #11
0
ファイル: Feedbacks.py プロジェクト: PetNamedEr/pts_feedback
def thankYou():
    # Shows an award and thank you message ONLY IF the survey is completed.
    # This should be checked when this action gets called.
    # The cookie should also be deleted.
    print('\n--- ENTERING thankYou, method: {}'.format(request.method))

    session.rollback()
    session.flush()

    feedback_id = request.cookies['feedback_id']
    feedback = session.query(Feedback).filter_by(id_=feedback_id).one()

    # Check that answer entries have been created for each survey question
    progress, missing, missing_mandatory = get_progress(feedback)
    print('---PROGRESS! {}'.format(progress))
    print('---MISSING! {}'.format(missing))
    print('---MISSING MANDATORY! {}'.format(missing_mandatory))
    # flash('progress: {}'.format(progress))
    # flash('missing: {}'.format(missing))
    # flash('missing_mandatory: {}'.format(missing_mandatory))
    # flash('Feedback_id == Cookie == {}'.format(feedback.id_))

    # If no mandatory answers missing
    if len(missing_mandatory) == 0:

        # This is a placeholder for actual gift
        gifts = {0: 'gift_1.png', 1: 'gift_2.png', 2: 'gift_3.png'}
        gift_ix = int(request.cookies['feedback_id']) % len(gifts)
        gift_file = '/static/imgs/{}'.format(gifts[gift_ix])

        response = make_response(
            render_template('survey_lastpage.html', gift_file=gift_file))
        response.set_cookie('feedback_id', '', expires=0)  # Delete cookie
        print(
            '---RESPONSE CREATED. EXITING thankYou AND RENDERING survey_lastpage.html: {}'
            .format(response))
        return response

    # If answers missing
    elif len(missing_mandatory) == 1:
        print('len(missing) == 1')
        return '<h3>Please fill in the following question:</h3><h4>{}</h4>'.format(
            list(missing_mandatory)[0])
    else:
        print('len(missing) > 1')
        return '<h3>Please fill in the following questions:</h3><h4>{}</h4>'.format(
            '<br>'.join(list(missing_mandatory)))
コード例 #12
0
ファイル: Surveys.py プロジェクト: PetNamedEr/pts_feedback
def surveys():
    form = SurveyForm(request.form)
    if request.method == 'GET':
      # the query returns list of all surveys and sends the list to the view:
      return render_template('surveys.html', surveys=session.query(Survey).order_by(Survey.id_).all())
    if (request.method == 'POST') and (form.validate()):
      if form.start_date.data < form.end_date.data:
        surveyToBeAdded = Survey(form.description.data,form.start_date.data, form.end_date.data, form.enabled.data)
        session.add(surveyToBeAdded) #adding record to database
        session.commit() #commiting addition

        return redirect("/surveys/" + str(surveyToBeAdded.id_) + "/questions")
      else:
        flash("Survey creation error: start_date is after end_date.")
        return render_template('new_survey.html', form=form)
    else:
      return render_template('new_survey.html', form=form)
コード例 #13
0
ファイル: Feedbacks.py プロジェクト: Arvinje/pts_feedback
def thankYou():
    # Shows an award and thank you message ONLY IF the survey is completed.
    # This should be checked when this action gets called.
    # The cookie should also be deleted.
    session.rollback()
    session.flush()

    feedback_id = request.cookies['feedback_id']
    feedback = session.query(Feedback).filter_by(id_=feedback_id).one()

    # Check that answer entries have been created for each survey question
    progress, missing = get_progress(feedback)

    response = make_response(render_template('survey_lastpage.html'))
    # response = make_response(render_template('survey_lastpage.html', gift_file=gift_file))
    response.set_cookie('feedback_id', '', expires=0)  # Delete cookie
    return response
コード例 #14
0
ファイル: Questions.py プロジェクト: PetNamedEr/pts_feedback
def questions(survey_id):
    form = QuestionForm(request.form)
    if (request.method == 'GET'):
        return render_template(
            'questions.html',
            survey_id=survey_id,
            questions=session.query(Question).order_by(
                Question.id_).filter(Question.survey_id_ == survey_id).all())

    if (request.method == 'POST') and (form.validate()):
        newQuestion = Question(form.type_.data, form.title_.data, survey_id,
                               form.optional_.data)
        session.add(newQuestion)
        session.commit()
        return redirect("/surveys/" + str(survey_id) + "/questions")
    else:
        return render_template('edit_question.html', form=form)
コード例 #15
0
def editQuestionChoice(survey_id,question_id,questionChoice_id):
	form = QuestionChoiceForm(request.form)
	questionChoiceToBeEdited = session.query(QuestionChoice).filter(QuestionChoice.id_==questionChoice_id).one()

	if request.method == 'GET':
		# pre-filling the form:
		form.title_.data = questionChoiceToBeEdited.title_

		return render_template('edit_questionChoice.html', form=form)
	elif (request.method == 'POST') and (form.validate()):
		# editing the question:
		questionChoiceToBeEdited.title_ = form.title_.data

		session.add(questionChoiceToBeEdited)
		session.commit()
		return redirect("/surveys/" + str(survey_id) + "/questions/" + str(question_id) + "/questionChoices")
	else:
		return render_template('edit_questionChoice.html', form=form)
コード例 #16
0
def questionChoice(survey_id,question_id,questionChoice_id):
	return render_template('questionchoice.html',survey_id=survey_id,\
		questionChoices=session.query(QuestionChoice).order_by(QuestionChoice.id_).\
		filter(QuestionChoice.survey_id_ == survey_id, QuestionChoice.question_id_ == question_id,\
				QuestionChoice.id_ == questionChoice_id).\
			one())
コード例 #17
0
ファイル: Feedbacks.py プロジェクト: PetNamedEr/pts_feedback
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:')

    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))

    # Template dict
    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)
    }
    print('---FORM DICT: {}'.format(qtype_forms))

    progress = 0

    # GET: SHOW QUESTION
    if request.method == 'GET':
        print('\n--- ENTERING showQuestion with question_id: {}, method: {}'.
              format(question_id, request.method))

        # 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
        # flash('prev_q_ix: {}'.format(prev_q_ix))
        # flash('next_q_ix: {}'.format(next_q_ix))
        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
        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))

        # flash('Feedback_id == Cookie == {}'.format(feedback.id_))
        # flash('form.value_: {}'.format(form.value_))

        # Check for pre-existing answers
        try:
            print('---CHECK FOR PRE-EXISTING ANSWER:', type(q.id_), q.id_,
                  type(request.cookies['feedback_id']),
                  request.cookies['feedback_id'])
            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 ANSWERS:', pre_existing_answer)
        except:
            pre_existing_answer = None

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

            # Parse answer in db to response parameters for displaying it
            form = db_answer_to_response(pre_existing_answer, q.type_, form)
            print('form.value_.data == {} {}'.format(type(form.value_.data),
                                                     form.value_.data))
        else:
            print('---NO PRE-EXISTING ANSWER FOUND.')

        # Debug statements
        print('---TEMPLATE: {}, {}'.format(type(template), template))
        print('---FORM: {}, {}'.format(type(form), form))
        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, missing_mandatory = get_progress(feedback)

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

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

        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
                # downthumb_status=downthumb_status,
                # upthumb_status=upthumb_status,
            ))

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

        return response

    # POST QUESTION:
    elif request.method == 'POST':
        print('\n---ENTERING WITH POST')
        print('request.form: {}'.format(request.form))
        print('request.cookies: {}'.format(request.cookies))

        # Get possible pre-existing answer
        print('---COMPARING POSTED ANSWER TO POSSIBLY PRE-EXISTING ANSWER')
        answer = session.query(Answer).filter_by(
            feedback_id_=int(request.cookies['feedback_id']),
            question_id_=int(request.form['question_id'])).all()
        print('len(answer): {}'.format(len(answer)))
        if len(answer) > 0:
            print('---FOUND PRE-EXISTING ANSWER:')
            answer = answer[0]
            print(answer)
            print('---PRE-EXISTING answer.value_: {}'.format(answer.value_))

            # Parse
            parsed_answer = parse_answer_from_request_form(
                request.form, answer.value_)
            print('---PARSED_ANSWER: {}'.format(parsed_answer))

            if answer.value_ == parsed_answer:
                print('Scrolling through, did not change answer')
            else:
                print('---CHANGING PRE-EXISTING ANSWER')
                answer.value_ = parsed_answer
                print('---REPLACED VALUE OF PRE-EXISTING ANSWER WITH:')
                print(answer.serialize)
        else:
            # Create new answer object
            print('---NO PRE-EXISTING ANSWER FOUND!')

            parsed_answer = parse_answer_from_request_form(request.form, None)
            print('---PARSED_ANSWER: {}'.format(parsed_answer))

            answer = Answer(parsed_answer, int(request.cookies['feedback_id']),
                            int(request.form['question_id']))
            print('---CREATED NEW ANSWER OBJECT:')
            print('answer.serialize {}'.format(answer.serialize))
            print('---ANSWER.value_: {} {} len {}'.format(
                type(answer.value_), answer.value_, len(answer.value_)))

        # Validate: data required
        if len(answer.value_) > 0:
            session.add(answer)
            session.commit()

        # 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'])

        # Redirect to prev 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'])

        return 'POST redirection to next/prev failed'
コード例 #18
0
def question(survey_id, question_id):
    return render_template('questions.html',survey_id=survey_id,
     questions=session.query(Question).order_by(Question.id_).\
     filter(Question.survey_id_ == survey_id, Question.id_ == question_id).\
     all())
コード例 #19
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.

    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'
コード例 #20
0
ファイル: Feedbacks.py プロジェクト: PetNamedEr/pts_feedback
def newFeedback():
    # Creates a feedback record
    # Stores the id to that record in a cookie
    # Has respective view that shows the latest active survey
    print('\n--- ENTERING newFeedback, method: {}'.format(request.method))

    # Question types dict
    qtype_forms = {
        'Freeform': AnswerFormFree(request.form),
        'Thumbs': AnswerFormThumbs(request.form),
        'Stars': AnswerFormStars(request.form),
        'Smileys': AnswerFormSmileys(request.form),
        'Choices': AnswerFormChoices(request.form)
    }

    print('---FORM DICT: {}'.format(qtype_forms))

    # From active surveys, get one with greatest id
    survey = session.query(Survey).filter(
        Survey.end_date_ >= datetime.datetime.now(),
        Survey.enabled_).order_by(Survey.id_.desc()).first()
    if survey != None:
        print('--- FOUND SURVEY ID {}, TITLE {}'.format(
            survey.id_, survey.description_))
    else:
        return 'No active surveys.'

    # Check if valid cookie exists
    feedback = None
    try:
        cookie = request.cookies['feedback_id']
        if cookie == None:
            print('---FOUND COOKIE WITH VALUE None')
        else:
            # Fetch feedback with id_ == cookie from db
            feedback = session.query(Feedback).filter_by(id_=cookie).one()
            if feedback.survey_id_ == survey.id_:
                print(
                    '---FOUND VALID COOKIE WITH FEEDBACK_ID {} CONNECTED TO SURVEY {}'
                    .format(cookie, survey.id_))
            else:
                print('---FOUND INVALID COOKIE FOR THIS SURVEY:')
    except:
        pass

    # If no valid cookie exists, create new feedback and new cookie with feedback id_ as value
    if feedback == None or cookie == None or len(cookie) == 0:
        print(
            '--- NO COOKIE FOUND. CREATING NEW FEEDBACK RECORD FOR THIS SURVEY...'
        )
        feedback = Feedback(survey_id_=survey.id_)
        session.add(feedback)
        session.commit(
        )  # For some reason, feedback.survey_id_ is not yet entered into db. (((WHY)))

        # Workaround to store feedback.survey_id_ into db: query, change, commit
        feedback = session.query(Feedback).order_by(
            Feedback.id_.desc()).first()
        feedback.survey_id_ = survey.id_
        session.add(feedback)
        session.commit()

        # Check that feedback.survey_id_ is now stored in db
        feedback = session.query(Feedback).order_by(
            Feedback.id_.desc()).first()
        print('---CREATED FEEDBACK ENTRY {}'.format(feedback.serialize))
        print('--- COOKIE / SESSION ID WILL BE SET TO: {}'.format(
            feedback.id_))
    else:
        print('---FEEDBACK WAS NOT NONE, IT\'S: {}'.format(feedback.serialize))

    # Get list of survey questions
    q_list = session.query(Question).filter_by(survey_id_=survey.id_).order_by(
        Question.id_).all()
    print('---QUESTIONS FOR SURVEY {}: {}, len {}'.format(
        survey.id_, q_list, len(q_list)))

    # Get first question
    q, response = None, None
    try:
        q = q_list[0]
    except:
        return 'Survey has no questions. Thank you & goodbye.'

    # Show first survey question:
    if q != None:
        template = templates.get(
            q.type_,
            'freeform.html')  # Defaults to show_question_freeform for now
        form = qtype_forms.get(q.type_, AnswerFormFree(
            request.form))  # Defaults to AnswerFormFree for now
        prev_url = None
        next_url = url_for(
            'controllers.thankYou') if len(q_list) <= 1 else url_for(
                'controllers.showQuestion', question_id=q_list[1].id_)

        progress = 0

        # Debug statements
        print('---QUESTION TYPE: {}'.format(q.type_))
        print('---TEMPLATE: {}, {}'.format(type(template), template))
        print('---FORM: {}, {}'.format(type(form), form))
        print('---FIRST 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))

        # flash('Feedback_id == Cookie == {}'.format(feedback.id_))
        # flash('progress: {}'.format(progress))

        response = make_response(
            render_template('survey_frontpage.html',
                            survey=survey,
                            question_id=q.id_,
                            feedback=feedback,
                            progress=progress))

        # Set cookie to value of feedback.id_
        response.set_cookie('feedback_id', str(feedback.id_))
        print(
            '---RESPONSE CREATED. EXITING newFeedback AND RENDERING survey_frontpage.html: {}'
            .format(response))

    return response
コード例 #21
0
def surveyQuestionResults(survey_id, question_id):
    return render_template(
        'survey_question_results.html',
        question=session.query(Question).filter_by(survey_id_=survey_id,
                                                   id_=question_id).one(),
        survey=session.query(Survey).filter_by(id_=survey_id).one())
コード例 #22
0
def surveyResults(survey_id):
    return render_template(
        'survey_results.html',
        survey=session.query(Survey).filter_by(id_=survey_id).one())
コード例 #23
0
def surveyResultList():
    return render_template('survey_result_list.html', surveys=session.query(Survey).order_by(Survey.id_).\
      filter(Survey.start_date_ <= (time.strftime('%Y') + '-' + time.strftime('%m') + '-' + time.strftime('%d'))).all())
コード例 #24
0
ファイル: Feedbacks.py プロジェクト: Arvinje/pts_feedback
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'
コード例 #25
0
ファイル: Feedbacks.py プロジェクト: Arvinje/pts_feedback
def newFeedbackForSurvey(surveyID):
    # Creates a feedback record
    # Stores the id to that record in a cookie
    # Has respective view that shows the latest active survey

    # Form dict
    qtype_forms = {
        'Freeform': AnswerFormFree(request.form),
        'Thumbs': AnswerFormThumbs(request.form),
        'Stars': AnswerFormStars(request.form),
        'Smileys': AnswerFormSmileys(request.form),
        'Choices': AnswerFormChoices(request.form),
        'Picture': AnswerFormFree(request.form)
    }

    # From active surveys, get one with greatest id
    survey = session.query(Survey).filter(Survey.id_ == surveyID,
                                          Survey.enabled_).first()
    if survey == None:
        return 'No active surveys.'

    # Check if valid cookie exists
    feedback = None
    try:
        cookie = request.cookies['feedback_id']
        if not (cookie == None or (request.cookies['survey_id'] != surveyID)):
            # Fetch feedback with id_ == cookie from db
            feedback = session.query(Feedback).filter_by(id_=cookie).one()
    except:
        pass

    # If no valid cookie exists, create new feedback and new cookie with feedback id_ as value
    if feedback == None or cookie == None or len(cookie) == 0:
        feedback = Feedback(survey_id_=survey.id_)
        session.add(feedback)
        session.commit(
        )  # For some reason, feedback.survey_id_ is not yet entered into db. (((WHY)))

        # Workaround to store feedback.survey_id_ into db: query, change, commit
        feedback = session.query(Feedback).order_by(
            Feedback.id_.desc()).first()
        feedback.survey_id_ = survey.id_
        session.add(feedback)
        session.commit()

        # Check that feedback.survey_id_ is now stored in db
        feedback = session.query(Feedback).order_by(
            Feedback.id_.desc()).first()

    # Get list of survey questions
    q_list = session.query(Question).filter_by(survey_id_=survey.id_).order_by(
        Question.id_).all()

    # Get first question
    q, response = None, None
    try:
        q = q_list[0]
    except:
        return 'Survey has no questions. Thank you & goodbye.'

    # Show first survey question:
    if q != None:
        template = templates.get(
            q.type_,
            'freeform.html')  # Defaults to show_question_freeform for now
        form = qtype_forms.get(q.type_, AnswerFormFree(
            request.form))  # Defaults to AnswerFormFree for now
        prev_url = None
        next_url = url_for(
            'controllers.thankYou') if len(q_list) <= 1 else url_for(
                'controllers.showQuestion', question_id=q_list[1].id_)

        progress = 0

        response = make_response(
            render_template('survey_frontpage.html',
                            survey=survey,
                            question_id=q.id_,
                            feedback=feedback,
                            progress=progress))
        # Set cookie to value of feedback.id_
        response.set_cookie('feedback_id', str(feedback.id_))

    return response