zoukankan      html  css  js  c++  java
  • 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格式

  • 相关阅读:
    sort,uniq,wc,tr
    cut
    more,less,head,tail
    cat
    mv
    WordPress调用全文阅读和截取文章摘要
    板邓:css ol 列表序列号样式
    小板邓:wordpress如何扩展TinyMCE编辑器,添加自定义按钮及功能
    wordpress前台显示顶部管理工具导航条
    SQL的主键和外键的作用
  • 原文地址:https://www.cnblogs.com/jiakecong/p/14794481.html
Copyright © 2011-2022 走看看