2

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?

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
Happy Mittal
  • 3,667
  • 12
  • 44
  • 60

1 Answers1

2

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')
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Thanks. It works. In hindsight, I think I didn't realise that I can just store the name "Mike" in any global variable, and then access in the function hello. – Happy Mittal Jul 21 '19 at 16:24
  • @HappyMittal Glad to help. You can certainly use global variables for testing, but it is [not recommended](https://stackoverflow.com/questions/25273989/flask-global-variables-and-sessions) for production apps. – Ajax1234 Jul 21 '19 at 16:26