| 250 | |
| 251 | |
| 252 | def compress_request( |
| 253 | request: requests.PreparedRequest, |
| 254 | always: bool, |
| 255 | ): |
| 256 | deflater = zlib.compressobj() |
| 257 | if isinstance(request.body, str): |
| 258 | body_bytes = request.body.encode() |
| 259 | elif hasattr(request.body, 'read'): |
| 260 | body_bytes = request.body.read() |
| 261 | else: |
| 262 | body_bytes = request.body |
| 263 | deflated_data = deflater.compress(body_bytes) |
| 264 | deflated_data += deflater.flush() |
| 265 | is_economical = len(deflated_data) < len(body_bytes) |
| 266 | if is_economical or always: |
| 267 | request.body = deflated_data |
| 268 | request.headers['Content-Encoding'] = 'deflate' |
| 269 | request.headers['Content-Length'] = str(len(deflated_data)) |