在 Flask 要透過 url 傳值,可以在 route 設定規則,規則用範例說明如下:
@app.route('/user/< name >')
def user(name):
return 'hello, ' + username
這樣在網址輸入 /user/John ,就可以在網頁看到
hello, John
帶入樣板的話就是:
@app.route('/user/< name >')
def user(name):
return return render_template('user.html', name=name )
這樣在 template 就能看到內容:
hello, {{ name }}
也可以在丟入參數時限定變數格式,支援的類型有四種 str, int, float, path,套用的話就會像是:
@app.route('/product/<int:id>')
def userage(id):
return 'product id is ' + str(id)
以上就是基本的把參數帶到網址的做法。