1 class HttpResponse(HttpResponseBase): 2 """ 3 An HTTP response class with a string as content. 4 5 This content that can be read, appended to or replaced. 6 """ 7 8 streaming = False 9 10 def __init__(self, content=‘‘, *args, **kwargs): 11 super(HttpResponse, self).__init__(*args, **kwargs) 12 # Content is a bytestring. See the `content` property methods. 13 self.content = content 14 15 def serialize(self): 16 """Full HTTP message, including headers, as a bytestring.""" 17 return self.serialize_headers() + b‘\r\n\r\n‘ + self.content 18 19 if six.PY3: 20 __bytes__ = serialize 21 else: 22 __str__ = serialize 23 24 def _consume_content(self): 25 # If the response was instantiated with an iterator, when its content 26 # is accessed, the iterator is going be exhausted and the content 27 # loaded in memory. At this point, it‘s better to abandon the original 28 # iterator and save the content for later reuse. This is a temporary 29 # solution. See the comment in __iter__ below for the long term plan. 30 if self._base_content_is_iter: 31 self.content = b‘‘.join(self.make_bytes(e) for e in self._container) 32 33 @property 34 def content(self): 35 self._consume_content() 36 return b‘‘.join(self.make_bytes(e) for e in self._container) 37 38 @content.setter 39 def content(self, value): 40 if hasattr(value, ‘__iter__‘) and not isinstance(value, (bytes, six.string_types)): 41 self._container = value 42 self._base_content_is_iter = True 43 if hasattr(value, ‘close‘): 44 self._closable_objects.append(value) 45 else: 46 self._container = [value] 47 self._base_content_is_iter = False 48 49 def __iter__(self): 50 # Raise a deprecation warning only if the content wasn‘t consumed yet, 51 # because the response may be intended to be streamed. 52 # Once the deprecation completes, iterators should be consumed upon 53 # assignment rather than upon access. The _consume_content method 54 # should be removed. See #6527. 55 if self._base_content_is_iter: 56 warnings.warn( 57 ‘Creating streaming responses with `HttpResponse` is ‘ 58 ‘deprecated. Use `StreamingHttpResponse` instead ‘ 59 ‘if you need the streaming behavior.‘, 60 PendingDeprecationWarning, stacklevel=2) 61 if not hasattr(self, ‘_iterator‘): 62 self._iterator = iter(self._container) 63 return self 64 65 def write(self, content): 66 self._consume_content() 67 self._container.append(content) 68 69 def tell(self): 70 self._consume_content() 71 return len(self.content)
是跟着render来的
from django.http import
时间: 2024-12-08 18:44:43