• django 返回数据的几种常用姿势


    django 返回数据的几种常用姿势

    render

    1. 传入一个html,返回一个页面
    def case_list(request):
       return render(request, 'case_list.html')
    
    1. 传入一个html,再传入一个字典,字典的key和value作用于html

    home.html

    <h1>欢迎{{ username }}使用 接口测试平台</h1>
    

    views中的home函数

    def home(request):
    	return render(request, 'home.html', {'username': 'kangpc'})
    

    我们想要的结果是:kangpc显示在html中的username位置

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kBfwIs8T-1628229744634)(C:\Users\54718\AppData\Roaming\Typora\typora-user-images\image-20210110002224550.png)]

    HttpResponse

    传入一个字符串,在返回的页面上显示该字符串

    def home(request):
       return HttpResponse('这里是伟大的home页面')
    

    HttpResponseRedirect

    传入一个urls中配置的路由,重定向到指定的路由页面

    JsonResponse

    传入json对象返回给前端json,前后端分离就是用的这个姿势

    from django.shortcuts import render
    from django.http import HttpResponse, HttpResponseRedirect
    
    
    def case_list(request):
       # return HttpResponse('这里是伟大的用例库页面')
       # return HttpResponseRedirect('/welcome/')
       return JsonResponse({'code': 0, 'data': {}, 'message': '提交成功'})
    

    源码

    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):
             # safe 参数判断数据是否为字典形式,不是字典形式则抛TypeError异常     
             #如果safe为False则利用短路操作默认为False,以下条件不执行,代表可支持dict以外形式数据
            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 = {}
            # 设置content_type返回的数据格式为application/json
            kwargs.setdefault('content_type', 'application/json')
            # 将json_dumps_params打散,将data序列化
            data = json.dumps(data, cls=encoder, **json_dumps_params)
            super().__init__(content=data, **kwargs)
    
    import json
    data = [{'a':"A",'b':(2,4),'c':3.0}]
    res = repr(data)
    print ("data :", res)
    data_json = json.dumps(data)
    print(data_json)
    执行结果:
    data : [{'a': 'A', 'b': (2, 4), 'c': 3.0}]
    [{"a": "A", "b": [2, 4], "c": 3.0}]
    观察两次打印的结果,会发现Python对象被转成JSON字符串以后,跟原始的repr()输出的结果会有些特殊的变化,原字典中的元组被改成了json类型的数组。
    
    # json.dump可以传递很多参数:  json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, 
          separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
    # json_dumps_params为字典形式, 如果json.dump需要传递参数则可以指定json_dumps_params参数
    # 例: return JsonResponse(back_dic, safe=False, json_dumps_params={'ensure_ascii':False})
    
    def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
            allow_nan=True, cls=None, indent=None, separators=None,
            default=None, sort_keys=False, **kw):
        """Serialize ``obj`` to a JSON formatted ``str``.
    
        If ``skipkeys`` is true then ``dict`` keys that are not basic types
        (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
        instead of raising a ``TypeError``.
    
        If ``ensure_ascii`` is false, then the return value can contain non-ASCII
        characters if they appear in strings contained in ``obj``. Otherwise, all
        such characters are escaped in JSON strings.
    
        If ``check_circular`` is false, then the circular reference check
        for container types will be skipped and a circular reference will
        result in an ``OverflowError`` (or worse).
    
        If ``allow_nan`` is false, then it will be a ``ValueError`` to
        serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
        strict compliance of the JSON specification, instead of using the
        JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
    
        If ``indent`` is a non-negative integer, then JSON array elements and
        object members will be pretty-printed with that indent level. An indent
        level of 0 will only insert newlines. ``None`` is the most compact
        representation.
    
        If specified, ``separators`` should be an ``(item_separator, key_separator)``
        tuple.  The default is ``(', ', ': ')`` if *indent* is ``None`` and
        ``(',', ': ')`` otherwise.  To get the most compact JSON representation,
        you should specify ``(',', ':')`` to eliminate whitespace.
    
        ``default(obj)`` is a function that should return a serializable version
        of obj or raise TypeError. The default simply raises TypeError.
    
        If *sort_keys* is true (default: ``False``), then the output of
        dictionaries will be sorted by key.
    
        To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
        ``.default()`` method to serialize additional types), specify it with
        the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
    
        """
        # cached encoder
        if (not skipkeys and ensure_ascii and
            check_circular and allow_nan and
            cls is None and indent is None and separators is None and
            default is None and not sort_keys and not kw):
            return _default_encoder.encode(obj)
        if cls is None:
            cls = JSONEncoder
        return cls(
            skipkeys=skipkeys, ensure_ascii=ensure_ascii,
            check_circular=check_circular, allow_nan=allow_nan, indent=indent,
            separators=separators, default=default, sort_keys=sort_keys,
            **kw).encode(obj)
    
    
    _default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None)
    
    
  • 相关阅读:
    [转帖]Mootools源码分析03 Hash
    iphone的手势与触摸编程学习笔记
    怎样使项目中的cocos2d默认模板支持ARC内存管理
    xCode4.2下添加TableViewController会出现”Prototype cells“警告
    关于31天App教程示例中一些因SDK版本而出现的问题
    带你掌握二进制SCA检测工具的短板及应对措施
    HDZ城市行深圳站|AIoT时代,如何抓住智联生活的战略机会点?
    分析内部运行机制,教你解决Redis性能问题
    今天谈谈用户故事地图,不是用户故事
    云图说|ModelArts Pro:让AI开发更简单
  • 原文地址:https://www.cnblogs.com/kknote/p/16103430.html
Copyright © 2020-2023  润新知