Fix Response.text failing when body is set to a string#12138
Fix Response.text failing when body is set to a string#12138dhruvildarji wants to merge 1 commit intoaio-libs:masterfrom
Conversation
Handle str in the body setter by encoding it to bytes directly, mirroring the behavior of the text setter. Previously, setting body to a string would create a StringPayload, causing .text to fail with an AttributeError. Fixes aio-libs#2928
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #12138 +/- ##
==========================================
- Coverage 98.78% 98.78% -0.01%
==========================================
Files 128 128
Lines 45297 45330 +33
Branches 2403 2406 +3
==========================================
+ Hits 44748 44780 +32
Misses 390 390
- Partials 159 160 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. |
| if self.content_type == "application/octet-stream": | ||
| self.content_type = "text/plain" | ||
| if self.charset is None: | ||
| self.charset = "utf-8" | ||
|
|
||
| self._body = text.encode(self.charset) | ||
| self._compressed_body = None |
There was a problem hiding this comment.
Should we not just make this:
self.body = text
And avoid the code duplication?
There was a problem hiding this comment.
created a
StringPayloadwrapper that didn't always have a compatibledecodemethod.
Under what condition does it not have a compatible decode() method? It looks like it should work to me...
|
Could you fill out the PR template? Also, why does this cause a coverage drop in the http writer @ https://app.codecov.io/gh/aio-libs/aiohttp/pull/12138/indirect-changes#b01a901427ef6052963c0c1281a51872-R212 ? |
Summary
Setting
Response.bodyto a string and then accessingResponse.textwould fail with anAttributeErrorbecause the body setter created aStringPayloadwrapper that didn't always have a compatibledecodemethod.The fix handles
strexplicitly in the body setter by encoding it directly to bytes, consistent with how thetextsetter works. It also sets sensible defaults forcontent_typeandcharsetwhen they haven't been configured.What's Changed
strhandling inResponse.bodysetter that encodes to bytes using the configured charsetcontent_typetotext/plainif it was the defaultapplication/octet-streamcharsettoutf-8if not already setTest Plan
Fixes #2928