{"id":"1eb90a30bb35c5f0","repo":"aio-libs/aiohttp","slug":"you-can-t-enable-chunked-encoding-when-a-content-l","errorCode":null,"errorMessage":"You can't enable chunked encoding when a content length is set","messagePattern":"You can't enable chunked encoding when a content length is set","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"aiohttp/web_response.py","lineNumber":177,"sourceCode":"        elif \"\\r\" in reason or \"\\n\" in reason:\n            raise ValueError(\"Reason cannot contain \\\\r or \\\\n\")\n        self._reason = reason\n\n    @property\n    def keep_alive(self) -> bool | None:\n        return self._keep_alive\n\n    def force_close(self) -> None:\n        self._keep_alive = False\n\n    @property\n    def body_length(self) -> int:\n        return self._body_length\n\n    def enable_chunked_encoding(self) -> None:\n        \"\"\"Enables automatic chunked transfer encoding.\"\"\"\n        if hdrs.CONTENT_LENGTH in self._headers:\n            raise RuntimeError(\n                \"You can't enable chunked encoding when a content length is set\"\n            )\n        self._chunked = True\n\n    def enable_compression(\n        self,\n        force: ContentCoding | None = None,\n        strategy: int | None = None,\n    ) -> None:\n        \"\"\"Enables response compression encoding.\"\"\"\n        # Don't enable compression if content is already encoded.\n        # This prevents double compression and provides a safe, predictable behavior\n        # without breaking existing code that may call enable_compression() on\n        # responses that already have Content-Encoding set (e.g., FileResponse\n        # serving pre-compressed files).\n        if hdrs.CONTENT_ENCODING in self._headers:\n            return\n        self._compression = True","sourceCodeStart":159,"sourceCodeEnd":195,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/c0ef574e29109210e96e652771ae4e7b88615fa4/aiohttp/web_response.py#L159-L195","documentation":"Raised as RuntimeError by StreamResponse.enable_chunked_encoding() (aiohttp/web_response.py:177) when a Content-Length header is already present in self._headers. HTTP does not allow both Transfer-Encoding: chunked and Content-Length on the same response - they imply conflicting framing - so aiohttp refuses rather than silently emit a malformed message.","triggerScenarios":"Calling resp.enable_chunked_encoding() after setting Content-Length via resp.content_length = N, resp.headers['Content-Length'] = 'N', or constructing StreamResponse(headers={'Content-Length': '123'}). Triggered by both direct calls and middleware that flips chunked on for streaming bodies.","commonSituations":"Middleware that auto-enables chunked encoding on every response (including those with a known length); handlers that compute Content-Length then pass the response to a streaming helper; copying headers from an upstream response that already had Content-Length.","solutions":["Decide on one framing: either set Content-Length for fixed-size bodies, or enable chunked for streams - not both.","Remove Content-Length before calling enable_chunked_encoding(): resp.headers.popall('Content-Length', None).","Avoid blanket middleware that calls enable_chunked_encoding() unconditionally; check content_length first."],"exampleFix":"// before\nresp = web.StreamResponse(headers={\"Content-Length\": \"100\"})\nresp.enable_chunked_encoding()  # RuntimeError\n\n\n# after\nresp = web.StreamResponse()\nresp.enable_chunked_encoding()  # no Content-Length set","handlingStrategy":"validation","validationCode":"if \"Content-Length\" not in resp.headers:\n    resp.enable_chunked_encoding()","typeGuard":"def can_enable_chunked(resp: web.StreamResponse) -> bool:\n    return \"Content-Length\" not in resp.headers and not resp._chunked","tryCatchPattern":"try:\n    resp.enable_chunked_encoding()\nexcept RuntimeError:\n    resp.headers.popall(\"Content-Length\", None)\n    resp.enable_chunked_encoding()","preventionTips":["Pick one framing strategy (chunked OR Content-Length), never both.","Avoid blanket middleware that flips chunked on unconditionally.","Remove Content-Length before calling enable_chunked_encoding()."],"tags":["http","response","chunked","framing"],"analyzedSha":"c0ef574e29109210e96e652771ae4e7b88615fa4","analyzedAt":"2026-08-04T19:51:05.467Z","schemaVersion":2}