路由 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