1. 程式人生 > >Flask中URL構建

Flask中URL構建

request quick nts route res app pen 函數名 imp

Flask QuickStart Refence

URL Building

To build a URL to a specific function, use the url_for() function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.

Flask 快速參考相關(譯文)

URL 構建

url_for() 函數用於構建指定函數的 URL。第一個參數為函數名,同時可以有多個對應於URL中變量的關鍵字參數,而未知變量將添加到 URL 中作為查詢參數。

舉例說明

from flask import Flask, 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 ‘{}\‘s profile‘.format(username)

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

Flask中URL構建