当前位置:网站首页>Flask (IV) -- URL construction

Flask (IV) -- URL construction

2022-06-11 09:27:00 zju_ cbw

url_for() Functions are important for building specific functions dynamically URL Very useful . This function takes the name of the function as the first argument , And accept one or more keyword parameters , Each parameter corresponds to URL The variable part of .


The following script demonstrates using 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 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 user function ( name ), It receives from URL Parameter values for .

User() Function to check whether the received parameter is consistent with admin matching . If the match , Then use url_for() Redirect application to hello_admin() function , Otherwise, take the received parameter as guest Parameter passed to hello_guest() function .

Run the script above , Open the browser and type URL - http://localhost:5000/user/admin. The browser outputs the following Hello Admin

Enter the following in the browser URL - http://localhost:5000/user/mvl. The browser outputs the following Hello mvl as Guest

原网站

版权声明
本文为[zju_ cbw]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012301369689.html