aio-libs/aiohttp · error · RuntimeError
You can't set content length when chunked encoding is enable
Error message
You can't set content length when chunked encoding is enable
What it means
The StreamResponse.content_length setter refuses to assign a value when _chunked is already True — the inverse of error 218. Once a response is committed to chunked transfer you cannot switch it back to a fixed Content-Length.
Solutions
- Set content_length BEFORE calling enable_chunked_encoding().
- Do not mix chunked and fixed-length on the same response.
- If you must reset, drop the Content-Length header instead of toggling modes.
Example fix
# before resp.enable_chunked_encoding() resp.content_length = size # after resp.content_length = size # do NOT enable chunked on this response
Defensive patterns
Strategy: validation
Validate before calling
if resp._chunked:
raise RuntimeError('response already chunked')
resp.content_length = size Prevention
- Set content_length BEFORE enable_chunked_encoding().
- Pick one transfer mode per response and stick to it.
- Do not toggle chunked on then try to assign a fixed length.
When it happens
Trigger: resp.enable_chunked_encoding() followed by resp.content_length = N.
Common situations: Streaming setup followed by an attempt to set length (e.g., for a HEAD request or after computing the size); copy-paste from a fixed-length handler into a chunked one.
Related errors
- You can't enable chunked encoding when a content length is…
- chunked can not be set if Content-Length header is set
- chunked can not be set if "Transfer-Encoding: chunked"…
- Not enough data to satisfy transfer length header.
- Request has duplicate `chunked` Transfer-Encoding
AI-assisted analysis of aio-libs/aiohttp@d041d4d0fd (2026-08-11).
Data as JSON: /api/errors/b20e27e61407c392.
Report an issue: GitHub.
Appendix: source
Thrown at aiohttp/web_response.py:213
self._compression = True
self._compression_force = force
self._compression_strategy = strategy
@property
def headers(self) -> "CIMultiDict[str]":
return self._headers
@property
def content_length(self) -> int | None:
# Just a placeholder for adding setter
return super().content_length
@content_length.setter
def content_length(self, value: int | None) -> None:
if value is not None:
value = int(value)
if self._chunked:
raise RuntimeError(
"You can't set content length when chunked encoding is enable"
)
self._headers[hdrs.CONTENT_LENGTH] = str(value)
else:
self._headers.pop(hdrs.CONTENT_LENGTH, None)
@property
def content_type(self) -> str:
# Just a placeholder for adding setter
return super().content_type
@content_type.setter
def content_type(self, value: str) -> None:
self.content_type # read header values if needed
self._content_type = str(value)
self._generate_content_type_header()
@propertyView on GitHub (pinned to d041d4d0fd)