HttpResponse
class HttpResponse(HttpResponseBase):
""" An HTTP response class with a string as content. This content that can be read, appended to or replaced. """
streaming = False
def __init__(self, content=b'', *args, **kwargs):
super(HttpResponse, self).__init__(*args, **kwargs)
# Content is a bytestring. See the `content` property methods.
self.content = content
return HttpResponse("hello world")
本质返回的就是HttpResponse对象
render
def render(request, template_name, context=None, content_type=None, status=None, using=None):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
return render(request, "login.html", local())
发现本质还是 HttpResponse来处理数据, 最终返回的还是HttpResponse对象
redirect
def redirect(to, *args, **kwargs):
"""
Returns an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
* A URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass permanent=True to issue a
permanent redirect
"""
if kwargs.pop('permanent', False):
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
return redirect_class(resolve_url(to, *args, **kwargs))
return redirect("/home.html")
返现最后调用了 redirect_class, 但是它指向的依然是HttpResponse对象
总结:
所有请求都会返回一个HttpResponse是对的!
本质 render, redirect源码里面返回的都是HttpResponse
JsonResponse
from django.http imoprt JsonResponse
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(JsonResponse, self).__init__(content=data, **kwargs)
这边对于参数 safe, json_dumps__params
可以发现 JsonResponse本值还是调用了 data = json.dumps(data, cls=encoder, **json_dumps_params)
对应 json_dumps__params 是为了解决相关的 中文编码不能正常显示问题 设置为key, value 方式传入参数就可以解决 json_dumps_params={"ensure_ascii":"False"}
对应 list 数据不能JsonResponse报错情况, 可以设置 safe=False 解决问题 ,取决于源码里的判断
if safe and not isinstance(data, dict):