我正在查看来自Django Official Docs的以下代码
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
然后我深入研究了django.http的源代码
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]
Q1:我们不应该使用return HttpResponse(content=html)
因为content
是在中定义的关键字参数def __init__(self, content=b'', *args, **kwargs):
吗?
Q2:装饰器在哪里@content.setter
定义?
Q3:何时何地self._container
定义属性?
Q4:命令的一切如何运作return HttpResponse(html)
?
发现了类似的问题Django的http.response的属性是什么?_container
,但我根本不明白答案。