Skip to content

Commit

Permalink
fix: Use Any for HttpResponse content argument (#212)
Browse files Browse the repository at this point in the history
Django can handle anything here, that can be converted to string.

----

Django uses make_bytes internally, and can convert anything with __iter__ method

```python

    @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 make_bytes(self, value):
        """Turn a value into a bytestring encoded in the output charset."""
        # Per PEP 3333, this response body must be bytes. To avoid returning
        # an instance of a subclass, this function returns `bytes(value)`.
        # This doesn't make a copy when `value` already contains bytes.

        # Handle string types -- we can't rely on force_bytes here because:
        # - Python attempts str conversion first
        # - when self._charset != 'utf-8' it re-encodes the content
        if isinstance(value, (bytes, memoryview)):
            return bytes(value)
        if isinstance(value, str):
            return bytes(value.encode(self.charset))
        # Handle non-string types.
        return str(value).encode(self.charset)
```
  • Loading branch information
last-partizan authored Nov 16, 2023
1 parent cdf62dd commit 6dfc2df
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion django-stubs/http/response.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class HttpResponse(HttpResponseBase, Iterable[bytes]):
test_was_secure_request: bool
xframe_options_exempt: bool
streaming: bool
def __init__(self, content: bytes = ..., *args: Any, **kwargs: Any) -> None: ...
def __init__(self, content: Any = ..., *args: Any, **kwargs: Any) -> None: ...
def serialize(self) -> bytes: ...
@property
def content(self) -> bytes: ...
Expand Down

0 comments on commit 6dfc2df

Please sign in to comment.