63

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")
shartshooter
  • 1,761
  • 5
  • 19
  • 40

1 Answers1

111

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))
starball
  • 20,030
  • 7
  • 43
  • 238
Adam Byrtek
  • 12,011
  • 2
  • 32
  • 32
  • 7
    If this is what you were looking for then feel free to upvote and/or accept the answer. – Adam Byrtek Nov 16 '14 at 19:58
  • 3
    Using redirect(url_for()) can an object be passed as a parameter? – tw1742 May 07 '16 at 04:02
  • 1
    I can't see why it should be like this. We can already do `defaults={. . .}` why can't we just chuck in a few arguments? – Luke Apr 28 '17 at 10:33
  • 1
    I have the same question as @tw1742. I am attempting to do exactly this but with a pandas dataframe and it doesn't seem to work. anyone know how to pass complex objects like dataframes? – greenteam May 30 '19 at 19:40
  • i think you can only pass serializable objects, as JSON objects, and there is a size limit that if exceeded the request gets ignored by the browsers @greenteam – BHA Bilel Jul 03 '20 at 23:04