Get a variable from the URL to all Flask routes

Issue

I try to create this little quiz page, but I’m not really familiar with Flask. Depending on which question I want to see, I can use a variable link, e.g. http://127.0.0.1:5000/question2. But I also need that question2 variable in the next route, but I’m not sure how to get it there. The way I tried it doesn’t seem to work:

questions_dict = {'question1':'What is number?', 'question2':'What is name?'}
answers_dict = {'question1':'10', 'question2':'Jack'}

@app.route('/<question>')
def home(question):
    return render_template('home.html', code=questions_dict.get(question))

@app.route('your_url', methods=['GET', 'POST'])
def your_url(question):
    if request.method == 'POST':
        answer = request.form['answer']
        if answer == answers_dict.get(question):
            full_filename = os.path.join('static', 'test.jpg')
            return render_template('your_url.html', user_image = full_filename)
        else:
            return render_template('again.html', code=questions_dict.get(question))

If the answer on the webpage matches the corresponding answer from the dictionary, it should display a picture. If not, go to the again.html page.

Solution

It appears that you’re using a form in home.html for capturing the answer. For capturing the question, you could add a hidden field to the same form, which you’d pre-populate via templating.

Alternatively, you could use GET /<question> for serving the question, and POST /<question> for checking the answer. In that case, you could use something like:

@app.route('/<question>', methods=['GET', 'POST'])
def route_question (question):
    if request.method == 'GET':
        return render_template('home.html', code=questions_dict.get(question))
    # otherwise ...
    answer = request.form['answer']
    if answer and answer == answers_dict.get(question):
        full_filename = os.path.join('static', 'test.jpg')
        return render_template('your_url.html', user_image = full_filename)
    # otherwise ...
    return render_template('again.html', code=questions_dict.get(question))

Do ensure that the form in home.html uses POST, i.e: <form method="POST">.

Such a solution would also apply with regard to similar WSGI frameworks, like Bottle and Vilo.

Answered By – Sumukh Barve

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published