我可以使用python请求库通过http-gzip或deflate压缩来发布数据吗?
问题描述:
我使用python 2.7的request-module将更大的数据块发布到我无法更改的服务中.由于数据主要是文本,因此它很大,但压缩效果很好.服务器可以接受gzip或deflate编码,但是我不知道如何指示请求执行POST并自动正确编码数据.
I use the request-module of python 2.7 to post a bigger chunk of data to a service I can't change. Since the data is mostly text, it is large but would compress quite well. The server would accept gzip- or deflate-encoding, however I do not know how to instruct requests to do a POST and encode the data correctly automatically.
是否有一个最小的示例,说明如何做到这一点?
Is there a minimal example available, that shows how this is possible?
答
# Works if backend supports gzip
additional_headers['content-encoding'] = 'gzip'
request_body = zlib.compress(json.dumps(post_data))
r = requests.post('http://post.example.url', data=request_body, headers=additional_headers)