如何将参数传递给Flask的重定向

如何将参数传递给Flask的重定向

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

问题描述

我想了解如何最好的使用Flask重定向和传递参数

下面是我的代码,我发现 code
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ :
返回render_template( found.html,
键=电子邮件,OBJ = listOfObjects)

@ app.route( '/查找',方法= [ 'GET' ,'POST'])
def find():$ b $如果request.method =='POST':
x = 3
y = 4
return redirect(url_for 'found',keys = x,obj = y))

return render_template(find.html)


解决方案

重定向很好,问题出在找到路由。您有几种方法可以将值传递给端点:作为路径的一部分,在URL参数(用于GET请求)或请求主体(用于POST请求)。



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

  @ app.route('/ found /< email> / < listOfObjects>')
DEF发现(电子邮件,listOfObjects):
返回render_template( found.html,
键=电子邮件,OBJ = listOfObjects)

另外:

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

另外,您的重定向应该提供请求参数,参数:

$ $ p $ code $ return return(url_for('found',email = x,listOfObjects = y))
code>

希望有帮助。


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

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

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")
解决方案

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)

Alternatively:

@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))

Hope that helps.

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

08-23 00:21