An HTTP response class with a string as content. This content can be read, appended to, or replaced.
| 368 | |
| 369 | |
| 370 | class HttpResponse(HttpResponseBase): |
| 371 | """ |
| 372 | An HTTP response class with a string as content. |
| 373 | |
| 374 | This content can be read, appended to, or replaced. |
| 375 | """ |
| 376 | |
| 377 | streaming = False |
| 378 | |
| 379 | def __init__(self, content=b"", *args, **kwargs): |
| 380 | super().__init__(*args, **kwargs) |
| 381 | # Content is a bytestring. See the `content` property methods. |
| 382 | self.content = content |
| 383 | |
| 384 | def __repr__(self): |
| 385 | return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % { |
| 386 | "cls": self.__class__.__name__, |
| 387 | "status_code": self.status_code, |
| 388 | "content_type": self._content_type_for_repr, |
| 389 | } |
| 390 | |
| 391 | def serialize(self): |
| 392 | """Full HTTP message, including headers, as a bytestring.""" |
| 393 | return self.serialize_headers() + b"\r\n\r\n" + self.content |
| 394 | |
| 395 | __bytes__ = serialize |
| 396 | |
| 397 | @property |
| 398 | def content(self): |
| 399 | return b"".join(self._container) |
| 400 | |
| 401 | @content.setter |
| 402 | def content(self, value): |
| 403 | # Consume iterators upon assignment to allow repeated iteration. |
| 404 | if hasattr(value, "__iter__") and not isinstance( |
| 405 | value, (bytes, memoryview, str) |
| 406 | ): |
| 407 | content = b"".join(self.make_bytes(chunk) for chunk in value) |
| 408 | if hasattr(value, "close"): |
| 409 | try: |
| 410 | value.close() |
| 411 | except Exception: |
| 412 | pass |
| 413 | else: |
| 414 | content = self.make_bytes(value) |
| 415 | # Create a list of properly encoded bytestrings to support write(). |
| 416 | self._container = [content] |
| 417 | self.__dict__.pop("text", None) |
| 418 | |
| 419 | @cached_property |
| 420 | def text(self): |
| 421 | return self.content.decode(self.charset or "utf-8") |
| 422 | |
| 423 | def __iter__(self): |
| 424 | return iter(self._container) |
| 425 | |
| 426 | def write(self, content): |
| 427 | self._container.append(self.make_bytes(content)) |
no outgoing calls