Flask(1) - 關於 app.route()
關於 app.route() 其實還有一些特性可以探討:
- 綁定多個 URL 到同個 function
- 動態 URL (傳遞變量)
1. 綁定多個 URL:
我們可以綁定多個 URL 到同一個 View function:
from flask import Flask
app = Flask(__name__)
@app.route("/hello")
@app.route("/hi")
def greet():
return "<h1 style=color:blue>Hello world</h1>"
預設 URL 會是 http://127.0.0.1:5000/hi 或是 http://127.0.0.1:5000/hello
2. 動態 URL:
我們可以把 URL 的一部分當作參數傳給 View function:
@app.route("/dessert/<name>")
def dessert(name):
return "<h1>Do you want to get some {}?</h1>".format(name)
例如我們輸入 http://127.0.0.1:5000/dessert/chocolate 就會得到 Do you want to get some chocolate?
3. 幫動態 URL 設定預設值:
app.route() 的 default 參數可以傳入一個字典,這個字典可以傳遞給 View function
@app.route("/dessert", defaults={"name": "chocolate"})
@app.route("/dessert/>name&rt;")
def dessert(name):
return "<h1>Do you want to get some {}?</h1>".format(name)
當我們輸入 http://127.0.0.1:5000/dessert 會得到 Do you want to get some chocolate?,因為 deafaults 提供了 name 參數給 dessert()。
留言
張貼留言