本文我們以一個(gè)登錄例子來(lái)說(shuō)明Flask對(duì) post請(qǐng)求的處理機(jī)制。
1、創(chuàng)建應(yīng)用目錄,如
mkdir examplecd example
2、在應(yīng)用目錄下創(chuàng)建 run.py文件,內(nèi)容如下
from flask import Flaskfrom flask import render_template, redirect,url_forfrom flask import requestapp = 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)上面的代碼用到了幾個(gè)flask的方法
render_template : 將請(qǐng)求定位到模板文件上,處理模板文件后,將結(jié)果作為請(qǐng)求的響應(yīng)返回
redirect:將請(qǐng)求的響應(yīng)重定向到新的url上。上面的例子是,當(dāng)?shù)卿洺晒螅囟ㄏ虻?home頁(yè)面。
url_for:根據(jù)參數(shù)生成url
2)request對(duì)象的使用
request對(duì)象包含了所有的請(qǐng)求信息,通過(guò)它可獲取所需要的請(qǐng)求信息。
3)app.route增加了methods參數(shù),指明該url支持的http請(qǐng)求方式,默認(rèn)是get方式。上面例子 /login即作為get,也作為post的請(qǐng)求目標(biāo)。
3、在應(yīng)用目錄下創(chuàng)建 templates目錄,在templates目錄下創(chuàng)建 login.html 和 home.html,內(nèi)容分別如下:
1)login.html文件
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="utf-8"> <title>login</title> </head> <body> <form style="margin:20px;border:1px solid red" method="post" action="/login"> <span>username:</span><input type="text" name="username" id="username"><br/> <span>password:</span><input type="password" name="password" id="password"><br/> <button type="submit" id="loginBtn">login</button> </form> {% if error %} <h1 style="color:red">{{ error }}!</h1> {% endif %} </body></html>2)home.html
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="utf-8"> <title>home</title> </head> <body> <h1>wlcome {{username}} , this is home</h1> </body></html>4、啟動(dòng)服務(wù)
在應(yīng)用目錄下運(yùn)行 python run.py
5、測(cè)試訪問(wèn)
http://192.168.142.138/login
注意:登錄成功后,會(huì)進(jìn)入 http://192.168.142.138/home?username=admin 頁(yè)面
這個(gè)url顯示不好。可以通過(guò)session的方式來(lái)不需要將username傳入,而是在home.html中通過(guò)session獲取。
這個(gè)在后面的文章中介紹。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選