1. 程式人生 > 其它 >DAY 212 Flask response 響應物件和make_response()方法

DAY 212 Flask response 響應物件和make_response()方法

Flask檢視函式返回的不僅僅是字串,而是會對返回值進行一些列的封裝,變成一個response響應對

如果檢視函式單純返回"****"的字串的話,flask會自動進行一些封裝讓他變成瀏覽器可以讀取的格式,也就是content-type = text/html,狀態碼為200。

我們可以使用Flask提供的make_response 方法來自定義自己的response物件

make_response()方法說明

1.返回內容

2.返回頁面

>>>注意:make_response 想要返回頁面,不能直接寫做:make_response('hello.html'),必須用render_template('hello.html')形式。

3.返回狀態碼

>>>方式一:在make_response()中傳入狀態碼

>>>方式二:直接return狀態碼

官方文件
make_response(rv)¶

Convert the return value from a view function to an instance of response_class.

Parameters

rv –

the return value from the view function. The view function must return a response. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv:

str (unicode in Python 2) 可以傳入一個字串物件,它將被編碼為UTF-8並被顯示在body中

A response object is created with the string encoded to UTF-8 as the body.

bytes (str in Python 2)

A response object is created with the bytes as the body.

dict 也可以傳入一個字典型別的物件,它將被先變成json格式再返回

A dictionary that will be jsonify’d before being returned.

tuple 也可以傳入一個元組,包含兩個或者三個元素,分別是body內容,status狀態碼,headers響應頭(字典型別)

Either (body, status, headers), (body, status), or (body, headers), where body is any of the other types allowed here, status is a string or an integer, and headers is a dictionary or a list of (key, value) tuples. If body is a response_class instance, status overwrites the exiting value and headers are extended.

這裡的元組的意思是我們可以再函式中直接通過return來返回這三個或者兩個物件,而不需要使用make_response()方法,Flask會自動進行識別和封裝。

例: