怎么在Flaskweb中處理POST請求登錄案例)-創(chuàng)新互聯(lián)
怎么在Flask web中處理POST請求登錄案例)?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
1、創(chuàng)建應(yīng)用目錄,如
mkdir example cd example
2、在應(yīng)用目錄下創(chuàng)建 run.py文件,內(nèi)容如下
from flask import Flask from flask import render_template, redirect,url_for from flask import request app = Flask(__name__) @app.route('/login', methods=['POST','GET']) def login(): error = None if request.method == 'POST': if request.form['username']=='admin': return redirect(url_for('home',username=request.form['username'])) else: error = 'Invalid username/password' return render_template('login.html', error=error) @app.route('/home') def home(): return render_template('home.html', username=request.args.get('username')) if __name__ == '__main__': app.debug = True app.run('0.0.0.0',80)
上面的代碼解釋如下:
1)上面的代碼用到了幾個flask的方法
render_template : 將請求定位到模板文件上,處理模板文件后,將結(jié)果作為請求的響應(yīng)返回
redirect:將請求的響應(yīng)重定向到新的url上。上面的例子是,當(dāng)?shù)卿洺晒螅囟ㄏ虻?home頁面。
url_for:根據(jù)參數(shù)生成url
2)request對象的使用
request對象包含了所有的請求信息,通過它可獲取所需要的請求信息。
3)app.route增加了methods參數(shù),指明該url支持的http請求方式,默認(rèn)是get方式。上面例子 /login即作為get,也作為post的請求目標(biāo)。
3、在應(yīng)用目錄下創(chuàng)建 templates目錄,在templates目錄下創(chuàng)建 login.html 和 home.html,內(nèi)容分別如下:
1)login.html文件
login
2)home.html
home wlcome {{username}} , this is home
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
新聞名稱:怎么在Flaskweb中處理POST請求登錄案例)-創(chuàng)新互聯(lián)
本文鏈接:http://www.xueling.net.cn/article/djehis.html