简体   繁体   English

传递变量以在烧瓶中重定向 url_for

[英]Passing a variable to redirect url_for in flask

I was wondering if it is possible to pass a value through redirect(url_for()) with out it becoming a GET.我想知道是否有可能通过redirect(url_for())传递值redirect(url_for())将其变成 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?如何将消息传递给 home 函数? 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()) ?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 /?mgs='logged out'.只给我一个带有 get /?mgs='logged out' 的 URL。

I understand that url_for is generating an url based on the name of the function being passed to it.我知道 url_for 正在根据传递给它的函数的名称生成一个 url。 Can you pass a value to that function?您可以将值传递给该函数吗?

What about a flash variable?闪光变量怎么样?

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

Then in template for home :然后在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/另见: http : //flask.pocoo.org/docs/0.12/patterns/flashing/

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:logout定义中,将消息存储在会话中:

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

In the home functionhome功能中

@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:home模板中,只需将其用作通常的变量:

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

This way you avoid using get and Flask takes care of all这样你就可以避免使用get并且 Flask 会处理所有

No, I Do not think so, but you can use GET parameters like:不,我不这么认为,但是您可以使用 GET 参数,例如:

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

and instead of using a template to do the work you can use JS而不是使用模板来完成工作,你可以使用 JS

Did you try this?你试过这个吗?

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

Code 307 is used as "POST"代码 307 用作“POST”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM