Django(26)HttpResponse對象和JsonResponse對象
HttpResponse對象
Django伺服器接收到客戶端發送過來的請求後,會將提交上來的這些數據封裝成一個HttpRequest
對象傳給視圖函數。那麼視圖函數在處理完相關的邏輯後,也需要返回一個響應給瀏覽器。而這個響應,我們必須返回HttpResponseBase
或者他的子類的對象。而HttpResponse
則是HttpResponseBase
用得最多的子類。那麼接下來就來介紹一下HttpResponse
及其子類。
常用屬性
- content:返回的內容。
- status_code:返回的HTTP響應狀態碼。
- content_type:返回的數據的MIME類型,默認為
text/html
。瀏覽器會根據這個屬性,來顯示數據。如果是text/html
,那麼就會解析這個字元串,如果text/plain
,那麼就會顯示一個純文本。常用的Content-Type
如下:- text/html(默認的,html文件)
- text/plain(純文本)
- text/css(css文件)
- text/javascript(js文件)
- multipart/form-data(文件提交)
- application/json(json傳輸)
- application/xml(xml文件)
- 設置請求頭:
response['X-Access-Token'] = 'xxxx'
。
常用方法
- set_cookie:用來設置
cookie
資訊。 - delete_cookie:用來刪除
cookie
資訊。 - write:
HttpResponse
是一個類似於文件的對象,可以用來寫入數據到數據體(content)中。
JsonResponse類
用來將對象dump
成json
字元串,然後返回將json
字元串封裝成Response
對象返回給瀏覽器。並且他的Content-Type
是application/json
。示例程式碼如下:
from django.http import JsonResponse
def index(request):
return JsonResponse({"username":"jkc","age":18})
默認情況下JsonResponse
只能對字典進行dump
,如果想要對非字典的數據進行dump
,那麼需要給JsonResponse
傳遞一個safe=False
參數。示例程式碼如下:
def index(request):
list1 = [
{"username": "jkc", "age": 18},
{"username": "a", "age": 20},
{"username": "b", "age": 22},
]
return JsonResponse(list1, safe=False)
上述程式碼我們定義了一個列表,當我們想要把非字典格式的數據進行dump
,那麼就需要添加參數safe=False
JsonResponse類源碼分析
class JsonResponse(HttpResponse):
"""
An HTTP response class that consumes data to be serialized to JSON.
:param data: Data to be dumped into json. By default only ``dict`` objects
are allowed to be passed due to a security flaw before EcmaScript 5. See
the ``safe`` parameter for more information.
:param encoder: Should be a json encoder class. Defaults to
``django.core.serializers.json.DjangoJSONEncoder``.
:param safe: Controls if only ``dict`` objects may be serialized. Defaults
to ``True``.
:param json_dumps_params: A dictionary of kwargs passed to json.dumps().
"""
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder, **json_dumps_params)
super().__init__(content=data, **kwargs)
我們可以看到JsonResponse
是繼承於HttpResponse
,寫了一個初始化方法,方法中有5個參數
- data:需要轉換的數據
- encoder:json編碼器
- safe:控制是否只有
dict
對象可以序列化,默認為True - json_dumps_params:字典通過
json.dumps()
轉化
中間程式碼的翻譯是:如果safe
設置為True
並且data的數據類型不是dict
,那麼拋出一個TypeError
類型錯誤,如果json_dumps_params
為None
,kwargs
設定一個默認值content_type='application/json'
,規定了返回的是json
格式,最後把字典格式的數據轉換成json
格式