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

  1. Set content_length BEFORE calling enable_chunked_encoding().
  2. Do not mix chunked and fixed-length on the same response.
  3. 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

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


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()

    @property

View on GitHub (pinned to d041d4d0fd)