flask框架之after_request的用法


一:被裝飾的函數必須傳遞一個參數,這個參數用來接收,視圖函數的返回值

不加參數報錯:

@app.after_request
def handler_after_request():
    return jsonify({"a":1})

# 錯誤提示
TypeError: handler_after_request() takes 0 positional arguments but 1 was given

 

加參數

@app.after_request
def handler_after_request(response):
    return jsonify({"a":1})

# 返回
{"a":1}

 

二:參數的說明

視圖函數的返回值有多個屬性,且為Response Objects對象。官方文檔里面的解釋是:

The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. 
Quite often you don’t have to create this object yourself because make_response() will take care of that for you.
默認情況下在Flask中使用的響應對象。工作方式類似於Werkzeug中的response對象,但默認設置為具有HTML mimetype。通常您不必自己創建此對象,因為make_response()將為您處理這些問題。

 

屬性1:headers

@app.after_request
def handler_after_request(xx): 
    print(xx.headers)
    return jsonify({"a":1})

# 打印結果
GET / HTTP/1.1  200 
Content-Type: text/html; charset=utf-8
Content-Length: 232


Content-Type: text/html; charset=utf-8
Content-Length: 232

 

屬性2:status

200 OK

屬性3:status_code

200

屬性4:data,處理返回值,可以假如判斷條件,處理不同的返回值

@app.after_request
def handler_after_request(xx):
    print(xx.data)
    print(xx.data.decode("utf-8"))
    return_str = xx.data.decode("utf-8")
    return_dict = eval(return_str)
    if return_dict.get("code") == 0:
        return jsonify({"return":"ok"})
    else:
        return jsonify({"return":"fail"})


# 打印結果
b'{"code":0,"content":"xixi"}\n'
{"code":0,"content":"xixi"}
# 返回值
{"return":"ok"}

 

方法1:get_json

get_json(force=False, silent=False, cache=True)
Parse data as JSON.

If the mimetype does not indicate JSON (application/json, see is_json()), this returns None.

If parsing fails, on_json_loading_failed() is called and its return value is used as the return value.

Parameters
force – Ignore the mimetype and always try to parse JSON.

silent – Silence parsing errors and return None instead.

cache – Store the parsed JSON to return for subsequent calls.

 

例子

@app.after_request
def handler_after_request(xx):
    return_dict = xx.get_json()   # 直接使用xx.data取出的結果是byte類型的東西,get_json直接取出的是字典類型
    print(return_str,type(return_dict)
    return jsonify(return_dict)

# 打印結果
{'code': 0, 'content': 'xixi'} <class 'dict'>

# 返回結果
{"code":0,"content":"xixi"}

# 如果視圖函數沒有返回值就返回
None <class 'NoneType'>

 

 三:作用

(1)對視圖函數的返回值進行統一處理

 

 

 

 

 

 

 

 

 

 

# TODO


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM