如何将参数传递到 Flask 的 redirect(url_for()) 中? [英] How can I pass arguments into redirect(url_for()) of Flask?

查看:114
本文介绍了如何将参数传递到 Flask 的 redirect(url_for()) 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何最好地使用 Flask 重定向和传递参数

I'm trying to understand how best to redirect and pass arguments using Flask

下面是我的代码,我发现 xy 没有进入模板.

Below is my code, I'm finding that x and y are not making it into the template.

我的语法正确吗?我错过了一些基本的东西吗?我能够呈现模板,但我想重定向到 url /found,而不是仅仅返回 find.html

Is my syntax correct? Am I missing something basic? I am able to render the template, but I want to redirect to the url /found, rather than just returning the template for find.html

@app.route('/found')
def found(email,listOfObjects):
  return render_template("found.html",
      keys=email,obj=listOfObjects)

@app.route('/find', methods=['GET','POST'])
def find():
    if request.method == 'POST':
        x = 3
        y = 4
        return redirect(url_for('found',keys=x,obj=y))

    return render_template("find.html")

推荐答案

重定向没问题,问题出在 found 路由上.您可以通过多种方式将值传递给端点:作为路径的一部分、在 URL 参数中(对于 GET 请求)或请求正文(对于 POST 请求).

The redirect is fine, the problem is with the found route. You have several ways to pass values to an endpoint: either as part of the path, in URL parameters (for GET requests), or request body (for POST requests).

换句话说,您的代码应如下所示:

In other words, your code should look as follows:

@app.route('/found/<email>/<listOfObjects>')
def found(email, listOfObjects):
  return render_template("found.html",
      keys=email, obj=listOfObjects)

或者:

@app.route('/found')
def found():
  return render_template("found.html",
      keys=request.args.get('email'), obj=request.args.get('listOfObjects'))

此外,您的重定向应该提供请求参数,而不是模板参数:

Also, your redirection should provide request parameters, not template parameters:

return redirect(url_for('found', email=x, listOfObjects=y))

希望有所帮助.

这篇关于如何将参数传递到 Flask 的 redirect(url_for()) 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆