Flask redirecting to url passing parameters to function

I am new to the Flask, and I am stuck in a very basic program, which just greets user with ‘Hello’ followed by their name. I wrote the code as below:

@app.route('/hello/')
def hello(name):
    return "Hello %s"% name

@app.route('/')
def greet():
    guest = "Mike"
    return redirect(url_for('hello',name=guest))

In this, I want to print “Hello Mike” on the url "localhost:5000/hello". However, it gives an error. This error gets resolved by modifying the line @app.route('/hello/') to @app.route('/hello/<name>'), but it then means for every different user, it redirects to a different url.

So is there any way that the redirected URL remains the same, i.e. "localhost:5000/hello", but the function hello(name) still receives the argument?

Answer

A possibility is to use flask.session to store the name in the function of one route and make it accessible in another:

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

Thus, when the user navigates to localhost:5000, "Mike" is set as the name in the sessions, and when the user is redirected to localhost:5000/hello, the name value is accessed from the sessions and displayed on the screen.

This method can also be used with POST requests: when a user submits a form on the frontend, the target route can store the guest name as the input value from the form and then simply redirect:

 @app.route('/some_form_route', methods=['POST'])
 def greet():
   flask.session['guest'] = flask.request['name']
   return flask.redirect('/hello')

Leave a Reply

Your email address will not be published. Required fields are marked *