我是 Flask 的新手,我被困在一个非常基本的程序中,它只是用“Hello”跟用户的名字打招呼。我写的代码如下:
@app.route('/hello/')
def hello(name):
return "Hello %s"% name
@app.route('/')
def greet():
guest = "Mike"
return redirect(url_for('hello',name=guest))
在此,我想在 url "localhost:5000/hello"
上打印“Hello Mike” 。但是,它给出了一个错误。通过修改行 @app.route('/hello/')
可以解决此错误至@app.route('/hello/<name>')
,但这意味着对于每个不同的用户,它会重定向到不同的 url。
有什么办法可以让重定向的 URL 保持不变,即 "localhost:5000/hello"
,但是函数hello(name)
仍然收到争论吗?
最佳答案
一种可能性是使用flask.session
将名称存储在一个路由的函数中,并使其可以在另一个路由中访问:
import random, string
app.secret_key = ''.join(random.choice(string.ascii_letters) for _ in range(30))
#a secret key is required for flask.session
@app.route('/hello/')
def hello():
return f'Hello {flask.session["guest"]}'
@app.route('/')
def greet():
flask.session['guest'] = 'Mike'
return flask.redirect('/hello')
因此,当用户导航到 localhost:5000
时,"Mike"
将被设置为 session 中的名称,并且当用户重定向到 localhost:5000/hello
,名称值从 session 中访问并显示在屏幕上。
此方法也可以与 POST
请求一起使用:当用户在前端提交表单时,目标路由可以将访客姓名存储为表单中的输入值,然后简单地重定向:
@app.route('/some_form_route', methods=['POST'])
def greet():
flask.session['guest'] = flask.request['name']
return flask.redirect('/hello')
关于python - Flask 重定向到 url 将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132929/