{"record":{"id":"bd5ca33822f6fcc7","repo":"aio-libs/aiohttp","slug":"compress-can-not-be-set-if-content-encoding-header","errorCode":null,"errorMessage":"compress can not be set if Content-Encoding header is set","messagePattern":"compress can not be set if Content-Encoding header is set","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"aiohttp/client_reqrep.py","lineNumber":1210,"sourceCode":"            del self.headers[hdrs.COOKIE]\n\n        for name, value in cookies.items():\n            # Use helper to preserve coded_value exactly as sent by server\n            c[name] = preserve_morsel_with_coded_value(value)\n\n        self.headers[hdrs.COOKIE] = c.output(header=\"\", sep=\";\").strip()\n\n    def _update_content_encoding(\n        self, data: Any, compress: bool | Literal[\"deflate\", \"gzip\"]\n    ) -> None:\n        \"\"\"Set request content encoding.\"\"\"\n        self.compress = None\n        if not data:\n            return\n\n        if self.headers.get(hdrs.CONTENT_ENCODING):\n            if compress:\n                raise ValueError(\n                    \"compress can not be set if Content-Encoding header is set\"\n                )\n        elif compress:\n            if isinstance(compress, str) and compress not in {\"deflate\", \"gzip\"}:\n                raise ValueError(\n                    \"compress must be one of True, False, 'deflate', or 'gzip'\"\n                )\n            self.compress = compress if isinstance(compress, str) else \"deflate\"\n            self.headers[hdrs.CONTENT_ENCODING] = self.compress\n            self.chunked = True  # enable chunked, no need to deal with length\n\n    def _update_transfer_encoding(self) -> None:\n        \"\"\"Analyze transfer-encoding header.\"\"\"\n        te = self.headers.get(hdrs.TRANSFER_ENCODING, \"\").lower()\n\n        if \"chunked\" in te:\n            if self.chunked:\n                raise ValueError(","sourceCodeStart":1192,"sourceCodeEnd":1228,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/d041d4d0fd48c3f0832084d33be16cf1c4835f85/aiohttp/client_reqrep.py#L1192-L1228","documentation":"Raised by ClientRequest._update_content_encoding() when a request supplies both a manually-set Content-Encoding header and a truthy 'compress' parameter. These are mutually exclusive ways to request body compression, so aiohttp refuses the ambiguous combination with ValueError. The method resets self.compress and, if data is present and Content-Encoding is set, any compress!=False triggers the error.","triggerScenarios":"Calling session.post(url, data=body, headers={'Content-Encoding':'gzip'}, compress=True) — or compress='gzip'. _update_content_encoding sees the existing header plus a truthy compress and raises ValueError.","commonSituations":"Pre-compressing the body and setting the header, but also passing compress=True; copy-paste mixing two compression strategies; migrating code that manually gzipped payloads to the compress parameter without removing the header.","solutions":["Choose one strategy: either pass compress=True/ 'gzip' and let aiohttp handle it, OR pre-compress the body and set Content-Encoding yourself (with compress=False).","If you pre-compressed, drop compress or set compress=False.","If you want aiohttp to compress, remove the manual Content-Encoding header.","Verify data is non-empty; with no data the method returns early and compression is skipped."],"exampleFix":"# before\nawait session.post(url, data=gzipped_body,\n    headers={'Content-Encoding': 'gzip'}, compress=True)  # ValueError\n\n# after — let aiohttp compress (recommended)\nawait session.post(url, data=raw_body, compress='gzip')\n# or pre-compress yourself and don't pass compress\nawait session.post(url, data=gzipped_body, headers={'Content-Encoding': 'gzip'})","handlingStrategy":"validation","validationCode":"def prepare_compression(headers, data, compress):\n    # mutually exclusive: manual Content-Encoding vs compress param\n    if headers.get('Content-Encoding') and compress:\n        # pick one strategy\n        headers.pop('Content-Encoding')  # let aiohttp compress\n    return compress","typeGuard":"def compression_is_unambiguous(headers, compress) -> bool:\n    return not (headers.get('Content-Encoding') and compress)","tryCatchPattern":"try:\n    await session.post(url, data=body, headers=headers, compress=compress)\nexcept ValueError as e:\n    if 'Content-Encoding header is set' in str(e):\n        headers.pop('Content-Encoding', None)\n        await session.post(url, data=body, headers=headers, compress=compress)\n    else:\n        raise","preventionTips":["Pick exactly one compression strategy: the compress param OR a manual header.","When pre-compressing payloads, set compress=False explicitly.","Document in code comments which path owns Content-Encoding."],"tags":["client","request","compression","http-headers","configuration"],"backgroundTag":null,"analyzedSha":"d041d4d0fd48c3f0832084d33be16cf1c4835f85","analyzedAt":"2026-08-11T20:44:15.550Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}