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位置

image-20210110002224550

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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM