路由 URL

使用 Flask,URL 路由传统上使用装饰器完成。这些装饰器可用于静态路由,以及带参数的路由 URL。对于以下示例,假设此 Flask 脚本正在运行网站 www.example.com

@app.route("/")
def index():
    return "You went to www.example.com"

@app.route("/about")
def about():
    return "You went to www.example.com/about"

@app.route("/users/guido-van-rossum")
    return "You went to www.example.com/guido-van-rossum"

使用最后一个路由,你可以看到给定带有/ users /和配置文件名称的 URL,我们可以返回一个配置文件。由于为每个用户包含一个 @app.route() 会非常低效和混乱,Flask 提供从 URL 获取参数:

@app.route("/users/<username>")
def profile(username):
    return "Welcome to the profile of " + username

cities = ["OMAHA", "MELBOURNE", "NEPAL", "STUTTGART", "LIMA", "CAIRO", "SHANGHAI"]

@app.route("/stores/locations/<city>")
def storefronts(city):
    if city in cities:
        return "Yes! We are located in " + city
    else:
        return "No. We are not located in " + city