Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Last active July 8, 2022 20:30
Show Gist options
  • Save kgriffs/e5129dd0cf0b6e3bde44f4fc1bf32e5d to your computer and use it in GitHub Desktop.
Save kgriffs/e5129dd0cf0b6e3bde44f4fc1bf32e5d to your computer and use it in GitHub Desktop.
Compressed multipart form (file) upload using Python requests.
In [16]: data = {'some': 'data'}
In [17]: data_compressed = gzip.compress(json.dumps(data, ensure_ascii=False).encode())
In [18]: requests.post("https://httpbin.org/anything", files={"msg": ('message.json.gz', body_compressed)}).json()
Out[18]:
{'args': {},
'data': '',
'files': {'msg': 'data:application/octet-stream;base64,H4sIAGeLyGIC/6tWKs7PTVWyUlBKSSxJVKoFABmPLCMQAAAA'},
'form': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Content-Length': '186',
'Content-Type': 'multipart/form-data; boundary=c8efd8af2c6d7b1a375b14a8b548c0ef',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.28.0',
'X-Amzn-Trace-Id': 'Root=1-62c893f0-3518418039ad9996485c1bd9'},
'json': None,
'method': 'POST',
'origin': '98.245.210.217',
'url': 'https://httpbin.org/anything'}
@kgriffs
Copy link
Author

kgriffs commented Jul 8, 2022

Note that as per RFC 7578, content-encoding is not allowed; therefore the receiving app must either assume the request is always compressed, or key off the filename for the body part.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment