Django中的 JsonResponse 与 HttpResponse

Django中的 JsonResponse 与 HttpResponse

JsonResponse 对象:

这是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 是一个HTTP响应类,它使用将要序列化为JSON的数据。
这个类是HttpResponse的子类(继承了HttpResponse类),主要和父类的区别在于:

  1. 第一个参数:data,默认只能是字典类型,将被转换为JSON格式的对象;默认的参数 safe=True,如果传入的参数不是字典类型,那么它就会抛出TypeError的异常;如果将safe设置为False,那么data可以填入任何能被转换为JSON格式的对象,比如:list、tuple、set。
  2. 默认情况下:会将Content-Type设置为application/json
  3. json_dumps_params参数是一个字典,它将调用json.dumps()方法并将字典中的参数传入给该方法?

JsonResponse 与 HttpResponse:

# 如果使用HttpResponse,ajax还需要进行json解析
# views.py
return HttpResponse(json.dumps({'msg': 'ok!'}))

# index.html
var data=json.parse(data)
console.log(data.msg);
# 如果使用JsonResponse,两边都不需要进行json的序列化与反序列化,ajax接受的直接就是一个对象
# views.py
from django.http import JsonResponse
return JsonResponse({'msg': 'OK!'})

# index.html
console.log(data.msg);

本文转载自guoyunlong666的博客https://www.cnblogs.com/guoyunlong666/p/9099397.html

猜你喜欢

转载自blog.csdn.net/qq_42269354/article/details/89149980