時(shí)間:2023-02-09 10:21:01 | 來(lái)源:建站知識(shí)
時(shí)間:2023-02-09 10:21:01 來(lái)源:建站知識(shí)
在上篇文章中,我們學(xué)習(xí)了Flask框架——response響應(yīng)對(duì)象及request對(duì)象,這篇文章我們來(lái)學(xué)習(xí)Flask框架——重定向、url_for。redirect(location,code=302,Response=None)
其中:from flask import Flask, redirectapp=Flask(__name__)#路由裝飾器@app.route('/index')def index(): return "<a href='/register'>首頁(yè)</a>"@app.route('/register')def register(): return "<a href='/redirect'>跳轉(zhuǎn)重定向頁(yè)面redirect</a>"@app.route('/redirect')def get_redirect(): return redirect('/index',code=302,Response=None)if __name__ == '__main__': app.run(port=8080,debug=True)
這里我們使用了三次路由裝飾器與視圖函數(shù)并綁定URL鏈接,其URL分別為:http://127.0.0.1:8080/indexhttp://127.0.0.1:8080/registerhttp://127.0.0.1:8080/redirect
首先我們進(jìn)入第一個(gè)URL鏈接時(shí)并點(diǎn)擊首頁(yè)超鏈接就會(huì)跳轉(zhuǎn)到第二個(gè)URL鏈接頁(yè)面,跳轉(zhuǎn)頁(yè)面后,點(diǎn)擊跳轉(zhuǎn)重定向頁(yè)面的超鏈接就會(huì)跳轉(zhuǎn)到第一個(gè)URL鏈接頁(yè)面,而在瀏覽器那一欄的URL鏈接為:http://127.0.0.1:8080/index。@app.route('/',endpoint='視圖函數(shù)的別名')
為視圖函數(shù)起別名,那么怎么使用該別名呢?這時(shí)我們可以使用url_for()方法,語(yǔ)法結(jié)構(gòu)為:url_for('視圖函數(shù)名或視圖函數(shù)別名')
示例代碼如下所示:from flask import Flask, redirect, url_forapp=Flask(__name__)@app.route('/indexsdafsfsalkdhasfkljsdalf',endpoint='shouye') #添加endpoint參數(shù)為視圖函數(shù)其別名def index(): return "<a href='/redirect'>首頁(yè)</a>"@app.route('/redirect') def get_redirect(): return redirect(url_for('shouye'),code=302,Response=None) if __name__ == '__main__': app.run(port=8080,debug=True)
首先我們?yōu)榈谝粋€(gè)視圖函數(shù)添加了endpoint參數(shù)的值,該值就是視圖函數(shù)的另一個(gè)名字,這樣我們就可以通過(guò)url_for()方法并傳入endpoint參數(shù)的值,就可以指向返回第一個(gè)視圖函數(shù)的URL鏈接頁(yè)面。<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <form action="{{ url_for('use_urlfor') }}" method="get"> <input type="submit" value="提交"> </form></body></html>
這里我們?cè)贖TML模板中使用了url_for()方法并傳入了視圖函數(shù)名,當(dāng)然也可以傳入視圖函數(shù)的別名。from flask import Flask, render_templateapp = Flask(__name__)@app.route('/')def hello_world(): return render_template('index.html') #渲染index.html模板文件@app.route('/use_urlfor',endpoint='index')def use_urlfor(): return '在模板文件中使用url_for' #返回字符串if __name__ == '__main__': app.run()
運(yùn)行Flask程序,訪問(wèn)http://127.0.0.1:5000/并點(diǎn)擊提交就會(huì)跳轉(zhuǎn)頁(yè)面,跳轉(zhuǎn)的頁(yè)面顯示內(nèi)容為:在模板文件中使用url_for。關(guān)鍵詞:
客戶&案例
營(yíng)銷(xiāo)資訊
關(guān)于我們
客戶&案例
營(yíng)銷(xiāo)資訊
關(guān)于我們
微信公眾號(hào)
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。