{"record":{"id":"efe0c08e8859dd4a","repo":"aio-libs/aiohttp","slug":"cannot-compute-fallback-encoding-of-a-not-yet-read","errorCode":null,"errorMessage":"Cannot compute fallback encoding of a not yet read body","messagePattern":"Cannot compute fallback encoding of a not yet read body","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"aiohttp/client_reqrep.py","lineNumber":730,"sourceCode":"\n    def get_encoding(self) -> str:\n        ctype = self.headers.get(hdrs.CONTENT_TYPE, \"\").lower()\n        mimetype = parse_mimetype(ctype)\n\n        encoding = mimetype.parameters.get(\"charset\")\n        if encoding:\n            with contextlib.suppress(LookupError, ValueError):\n                return codecs.lookup(encoding).name\n\n        if mimetype.type == \"application\" and (\n            mimetype.subtype == \"json\" or mimetype.subtype == \"rdap\"\n        ):\n            # RFC 7159 states that the default encoding is UTF-8.\n            # RFC 7483 defines application/rdap+json\n            return \"utf-8\"\n\n        if self._body is None:\n            raise RuntimeError(\n                \"Cannot compute fallback encoding of a not yet read body\"\n            )\n\n        return self._resolve_charset(self, self._body)\n\n    async def text(self, encoding: str | None = None, errors: str = \"strict\") -> str:\n        \"\"\"Read response payload and decode.\"\"\"\n        await self.read()\n\n        if encoding is None:\n            encoding = self.get_encoding()\n\n        return self._body.decode(encoding, errors=errors)  # type: ignore[union-attr]\n\n    async def json(\n        self,\n        *,\n        encoding: str | None = None,","sourceCodeStart":712,"sourceCodeEnd":748,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/d041d4d0fd48c3f0832084d33be16cf1c4835f85/aiohttp/client_reqrep.py#L712-L748","documentation":"Raised by ClientResponse.get_encoding() when no charset can be determined from the Content-Type header or mimetype defaults, and the response body has not been read yet. get_encoding() falls back to charset detection on self._body, but if _body is None (unread) it cannot run the detector and raises RuntimeError. This typically means get_encoding()/text()/json() was called before read() in a streaming context.","triggerScenarios":"Calling resp.get_encoding() (or resp.text()/resp.json() in a path where read() hasn't populated _body) on a response whose Content-Type has no charset and is not JSON/RDAP, while _body is still None. text()/json() normally call read() first, so this most often arises from calling get_encoding() directly or from a custom code path.","commonSituations":"Calling get_encoding() manually before reading the body; a response with 'Content-Type: text/html' (no charset) where the app tries to detect encoding prematurely; subclassing ClientResponse and invoking encoding logic out of order.","solutions":["Call await resp.read() before resp.get_encoding() so _body is populated.","Prefer resp.text() / resp.json() which call read() internally.","If you control the server, send an explicit charset: 'Content-Type: text/html; charset=utf-8'.","Pass encoding explicitly to text(encoding='utf-8') to bypass detection."],"exampleFix":"# before\nenc = resp.get_encoding()  # _body is None -> RuntimeError\nbody = await resp.read()\n\n# after\nbody = await resp.read()\nenc = resp.get_encoding()  # now _body is available for fallback detection","handlingStrategy":"validation","validationCode":"async def safe_get_encoding(resp) -> str:\n    if resp._body is None:\n        await resp.read()  # populate body before detection\n    return resp.get_encoding()","typeGuard":"def body_is_read(resp) -> bool:\n    return getattr(resp, '_body', None) is not None","tryCatchPattern":"try:\n    enc = resp.get_encoding()\nexcept RuntimeError as e:\n    if 'not yet read body' in str(e):\n        await resp.read()\n        enc = resp.get_encoding()\n    else:\n        raise","preventionTips":["Always call await resp.read() before get_encoding().","Prefer resp.text() which handles encoding internally.","Send explicit charset headers from your server to avoid detection."],"tags":["client","response","encoding","usage"],"backgroundTag":null,"analyzedSha":"d041d4d0fd48c3f0832084d33be16cf1c4835f85","analyzedAt":"2026-08-11T20:44:15.550Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}