diff --git a/CHANGES/2928.bugfix.rst b/CHANGES/2928.bugfix.rst new file mode 100644 index 00000000000..89fe6f00f33 --- /dev/null +++ b/CHANGES/2928.bugfix.rst @@ -0,0 +1 @@ +Changed ``AttributeError`` to ``TypeError`` when accessing ``Response.text`` after setting ``body`` to a value that becomes a ``Payload`` without a ``decode`` method. diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index 387736509b9..a3644db3ea8 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -636,10 +636,13 @@ def body(self, body: Any) -> None: def text(self) -> str | None: if self._body is None: return None - # Note: When _body is a Payload (e.g. FilePayload), this may do blocking I/O - # This is generally safe as most common payloads (BytesPayload, StringPayload) - # don't do blocking I/O, but be careful with file-based payloads - return self._body.decode(self.charset or "utf-8") + try: + return self._body.decode(self.charset or "utf-8") + except AttributeError: + raise TypeError( + f"Unable to get text from body type {type(self._body).__name__}. " + f"Use the text setter or pass text= to Response() for string content." + ) @text.setter def text(self, text: str) -> None: