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類

用來將對象dumpjson字元串,然後返回將json字元串封裝成Response對象返回給瀏覽器。並且他的Content-Typeapplication/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_paramsNonekwargs設定一個默認值content_type='application/json',規定了返回的是json格式,最後把字典格式的數據轉換成json格式

Tags: