django返回数据的⼏种常⽤姿势django 返回数据的⼏种常⽤姿势
render
1. 传⼊⼀个html,返回⼀个页⾯
def case_list(request):
return render(request, 'case_list.html')
2. 传⼊⼀个html,再传⼊⼀个字典,字典的key和value作⽤于html
home.html
<h1>欢迎{{ username }}使⽤接⼝测试平台</h1>
views中的home函数
def home(request):
return render(request, 'home.html', {'username': 'kangpc'})
我们想要的结果是:kangpc显⽰在html中的username位置
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
``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
python json字符串转数组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 _de(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)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。