一、get方法 ,post方法
post請求在模板中要注意幾點:
(1)input標簽中,要寫name來標識這個value的key,方便后台獲取。
(2)在寫form表單的時候,要指定method='post'
,並且要指定action='/login/'
。
示例代碼:
<form action="{{ url_for('login') }}" method="post">
<table>
<tbody>
<tr>
<td>用戶名:</td>
<td><input type="text" placeholder="請輸入用戶名" name="username"></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="text" placeholder="請輸入密碼" name="password"></td>
</tr>
<tr>
<td><input type="submit" value="登錄"></td>
</tr>
</tbody>
</table>
</form>
二、g對象
g:global
1. g對象是專門用來保存用戶的數據的。
2. g對象在一次請求中的所有的代碼的地方,都是可以使用的。
使用步驟:
1.創建一個utils.py文件,用於測試除主文件以外的g對象的使用
utils.py
from flask import g # 引入g對象 def login_log(): print '當前登錄用戶是:%s' % g.username def login_ip(): print '當前登錄用戶的IP是:%s' % g.ip
2.在主文件中調用utils.py中的函數
from flask import Flask,g,request,render_template from utils import login_log,login_ip app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/login/',methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: username = request.form.get('username') password = request.form.get('password')
# 使用g對象 g.username = username g.ip = password login_log() login_ip() return '恭喜登錄成功!'
if __name__ == '__main__': app.run()
三、鈎子函數
鈎子的理解:
在程序正常運行的時候,程序按照A函數—->B函數的順序依次運行;鈎子函數可以插入到A函數到B函數運行中間從而,程序運行順序變成了A—->鈎子函數—->B函數。
Flask項目中有兩個上下文,一個是應用上下文(app),另外一個是請求上下文(request)。請求上下文request和應用上下文current_app都是一個全局變量。所有請求都共享的。Flask有特殊的機制可以保證每次請求的數據都是隔離的,即A請求所產生的數據不會影響到B請求。所以可以直接導入request對象,也不會被一些臟數據影響了,並且不需要在每個函數中使用request的時候傳入request對象。這兩個上下文具體的實現方式和原理可以沒必要詳細了解。只要了解這兩個上下文的四個屬性就可以了:
(1)request:請求上下文上的對象。這個對象一般用來保存一些請求的變量。比如method、args、form等。
(2)session:請求上下文上的對象。這個對象一般用來保存一些會話信息。
(3)current_app:返回當前的app。
(4)g:應用上下文上的對象。處理請求時用作臨時存儲的對象。
常用的鈎子函數
before_first_request:處理第一次請求之前執行。
實例代碼:
@app.before_first_request def first_request(): print 'first time request'
before_request:在每次請求之前執行。通常可以用這個裝飾器來給視圖函數增加一些變量。
實例代碼:
@app.before_request def before_request(): if not hasattr(g,'user'): setattr(g,'user','xxxx')
teardown_appcontext:不管是否有異常,注冊的函數都會在每次請求之后執行。
實例代碼:
@app.teardown_appcontext def teardown(exc=None): if exc is None: db.session.commit() else: db.session.rollback() db.session.remove()
源碼地址:https://gitee.com/FelixBinCloud/ZhiLiaoDemo/tree/master/ZhiLiao