flask系列八之請求方法、g對象和鉤子函數

1、get方法 ,post方法

post請求在模板中要注意幾點:html

(1)input標籤中,要寫name來標識這個value的key,方便後臺獲取。git

(2)在寫form表單的時候,要指定method='post',而且要指定action='/login/'flask

示例代碼:session

 <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>

2、g對象

g:global 
1. g對象是專門用來保存用戶的數據的。 
2. g對象在一次請求中的全部的代碼的地方,都是可使用的。app

使用步驟: 函數

1.建立一個utils.py文件,用於測試除主文件之外的g對象的使用post

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中的函數url

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()

3、鉤子函數

鉤子的理解:spa

在程序正常運行的時候,程序按照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

相關文章
相關標籤/搜索