[Flask] Flask URL construction (url redirection)

Flask URL construction

Flask URL construction

The url_for() function is very useful for dynamically constructing URLs for specific functions. The function accepts the name of the function as the first parameter, and one or more keyword parameters, each parameter corresponds to the variable part of the URL.

The following script demonstrates how to use the url_for() function:

from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/admin')
def hello_admin():
   return 'Hello Admin'
@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest
@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))
if __name__ == '__main__':
   app.run(debug = True)

The above script has a function user(name) , which accepts the value of the parameter from the URL.

The User() function checks whether the received parameter matches'admin' . If so, use the url_for () will be redirected to the application hello_admin () function, or to redirect the received parameters passed to it as a parameter guest hello_guest () function.

Save the above code and run it from the Python shell.

Open the browser and enter the URL-  http://localhost:5000/user/admin

The application response in the browser is:

Hello Admin

Enter the following URL in the browser-  http://localhost:5000/user/mvl

The application response is now changed to:

Hello mvl as Guest

Guess you like

Origin blog.csdn.net/u013066730/article/details/108075085