前言
通過url 位址可以通路一個網頁,Flask 架構使用 route() 裝飾器來把函數綁定到 URL。
路由
使用 route() 裝飾器來把函數綁定到 URL。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
if __name__ == '__main__':
app.run()
除了上面的寫死的路徑,url 還可以用變量
url 使用變量
url 使用變量能接受的類型
- string (預設值) 接受任何不包含斜杠的文本
- int 接受正整數
- float 接受正浮點數
- path 類似 string ,但可以包含斜杠
- uuid 接受 UUID 字元串
通過把 URL 的一部分标記為 <variable_name> 就可以在 URL 中添加變量。
标記的 部分會作為關鍵字參數傳遞給函數。通過使用 converter:variable_name
from markupsafe import escape
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {escape(username)}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return f'Post {post_id}'
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return f'Subpath {escape(subpath)}'
唯一的URL / 重定向行為
以下兩條規則的不同之處在于是否使用尾部的斜杠。
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
projects 的 URL 是中規中矩的,尾部有一個斜杠,看起來就如同一個檔案夾。
通路一個沒有斜杠結尾的 URL ( /projects )時 Flask 會自動進行重 定向,幫您在尾部加上一個斜杠( /projects/ )。
about 的 URL 沒有尾部斜杠,是以其行為表現與一個檔案類似。如果通路這 個 URL 時添加了尾部斜杠(
/about/
)就會得到一個 404 “未找到” 錯 誤。
這樣可以保持 URL 唯一,并有助于搜尋引擎重複索引同一頁面。
url_for() 函數
url_for() 函數用于建構指定函數的 URL。它把函數名稱作為第一個 參數。它可以接受任意個關鍵字參數,每個關鍵字參數對應 URL 中的變量。未知變量 将添加到 URL 中作為查詢參數。
為什麼不在把 URL 寫死在模闆中,而要使用反轉函數 url_for() 動态建構?
- 反轉通常比寫死 URL 的描述性更好。
- 您可以隻在一個地方改變 URL ,而不用到處亂找。
- URL 建立會為您處理特殊字元的轉義,比較直覺。
- 生産的路徑總是絕對路徑,可以避免相對路徑産生副作用。
- 如果您的應用是放在 URL 根路徑之外的地方(如在 /myapplication 中,不在 / 中), url_for() 會為您妥善處理。
例如,這裡我們使用 test_request_context() 方法來嘗試使用 url_for() 。
test_request_context() 告訴 Flask 正在處理一個請求,而實際上也許我們正處在互動 Python shell 之中, 并沒有真正的請求。
from flask import url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
@app.route('/login')
def login():
return 'login'
@app.route('/user/<username>')
def profile(username):
return f'{username}\'s profile'
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
/
/login
/login?next=/
/user/John%20Doe