-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
80 lines (55 loc) · 2.15 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from flask import Flask, request, render_template, redirect, flash, session
from flask_debugtoolbar import DebugToolbarExtension
from surveys import satisfaction_survey as survey
# key names will use to store some things in the session;
# put here as constants so we're guaranteed to be consistent in
# our spelling of these
RESPONSES_KEY = "responses"
app = Flask(__name__)
app.config['SECRET_KEY'] = "never-tell!"
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
debug = DebugToolbarExtension(app)
@app.route("/")
def show_survey_start():
"""Select a survey."""
return render_template("survey_start.html", survey=survey)
@app.route("/begin", methods=["POST"])
def start_survey():
"""Clear the session of responses."""
session[RESPONSES_KEY] = []
return redirect("/questions/0")
@app.route("/answer", methods=["POST"])
def handle_question():
"""Save response and redirect to next question."""
# get the response choice
choice = request.form['answer']
# add this response to the session
responses = session[RESPONSES_KEY]
responses.append(choice)
session[RESPONSES_KEY] = responses
if (len(responses) == len(survey.questions)):
# They've answered all the questions! Thank them.
return redirect("/complete")
else:
return redirect(f"/questions/{len(responses)}")
@app.route("/questions/<int:qid>")
def show_question(qid):
"""Display current question."""
responses = session.get(RESPONSES_KEY)
if (responses is None):
# trying to access question page too soon
return redirect("/")
if (len(responses) == len(survey.questions)):
# They've answered all the questions! Thank them.
return redirect("/complete")
if (len(responses) != qid):
# Trying to access questions out of order.
flash(f"Invalid question id: {qid}.")
return redirect(f"/questions/{len(responses)}")
question = survey.questions[qid]
return render_template(
"question.html", question_num=qid, question=question)
@app.route("/complete")
def complete():
"""Survey complete. Show completion page."""
return render_template("completion.html")