Passing a variable to redirect url_for in flask

Question:

I was wondering if it is possible to pass a value through redirect(url_for()) with out it becoming a GET.

Basic example: I have a home function:

@app.route("/")
def home(msg=None):
    return render_template("home.html", mgs=msg)

how can I pass an message to the home function?
In other words can I do this:

@app.route("/logout")
def logout():
    logout_user()
    return render_template('home.html', msg="logged out")

with redirect(url_for())?

this:

@app.route("/logout")
def logout():
    logout_user()
    return redirect(url_for('home', msg="logged out"))

just gives me the url with a get /?msg=’logged out’.

I understand that url_for is generating an url based on the name of the function being passed to it. Can you pass a value to that function?

Asked By: lciamp

||

Answers:

No, I Do not think so, but you can use GET parameters like:

redirect('home?msg=You%20are%20loged%20in')

and instead of using a template to do the work you can use JS

Answered By: Mohamed Emad

What about a flash variable?

flash("logged out")
return redirect(url_for('home'))

Then in template for home:

{% with passed = get_flash_messages() %}
{% if passed %}
    <!-- passed should contain 'logged out' -->
{% endif %}

see also: http://flask.pocoo.org/docs/0.12/patterns/flashing/

Answered By: cowbert

Another way to go is using sessions:

Dont forget to add it to your imports

from flask import Flask, ..., session

In logout definition store the message in the session:

@app.route("/logout")
def logout():
    logout_user()
    session['msg'] = "logged out"
    return redirect(url_for('home'))

In the home function

@app.route("/")
def home(msg=None):
    return render_template("home.html", msg=session['msg'])

In the home template just use it as a usual variable:

<p>Dear user, you have been {{ msg }} </p>

This way you avoid using get and Flask takes care of all

Answered By: sscalvo

Did you try this?

msg="logged out"
return redirect(url_for('home'),code=307)

Code 307 is used as "POST"

Answered By: Roger Hayashi

Just use an fstring in your route direction.

redirect(f'/route/{variable}
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.