Django学习——视图层HttpResponse、render、redirect本质、JsonResponse

HttpResponse、render、redirect本质

django视图函数必须要返回一个HttpResponse对象

def render(request, template_name, context=None, content_type=None, status=None, using=None):
"""
Return 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)

class HttpResponse(HttpResponseBase):
"""
An HTTP response class with a string as content.

This content can be read, appended to, or replaced.
"""

streaming = False

def init(self, content=b'', args, **kwargs):
super().init(
args, **kwargs)
# Content is a bytestring. See the content property methods.
self.content = content

def repr(self):
return '<%(cls)s status_code=%(status_code)d%(content_type)s>' % {
'cls': self.class.name,
'status_code': self.status_code,
'content_type': self._content_type_for_repr,
}

def serialize(self):
"""Full HTTP message, including headers, as a bytestring."""
return self.serialize_headers() + b'\r\n\r\n' + self.content

bytes = serialize

@property
def content(self):
return b''.join(self._container)

@content.setter
def content(self, value):
# Consume iterators upon assignment to allow repeated iteration.
if (
hasattr(value, 'iter') and
not isinstance(value, (bytes, memoryview, str))
):
content = b''.join(self.make_bytes(chunk) for chunk in value)
if hasattr(value, 'close'):
try:
value.close()
except Exception:
pass
else:
content = self.make_bytes(value)
# Create a list of properly encoded bytestrings to support write().
self._container = [content]

def iter(self):
return iter(self._container)

def write(self, content):
self._container.append(self.make_bytes(content))

def tell(self):
return len(self.content)

def getvalue(self):
return self.content

def writable(self):
return True

def writelines(self, lines):
for line in lines:
self.write(line)

redirect内部是继承了HttpResponse类

JsonResponse

需求:给前端返回json格式数据
方式1:自己序列化
# res = json.dumps(d,ensure_ascii=False)
# return HttpResponse(res)
方式2:JsonResponse
import json
from django.http import JsonResponse
def func2(request):
d = {'user':'jason好帅','password':123}
return JsonResponse(d)

ps:额外参数补充

json_dumps_params={'ensure_ascii':False} # 看源码
safe=False # 看报错信息

JsonResponse返回的也是HttpResponse对象

posted @ 2022-04-30 21:03  寻月隐君  阅读(114)  评论(0)    收藏  举报