Can I POST data with python requests lib with http-gzip or deflate compression?

后端 未结 5 1785
深忆病人
深忆病人 2021-02-13 03:39

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

5条回答
  •  盖世英雄少女心
    2021-02-13 04:38

    For python 3:

    from io import BytesIO
    import gzip
    
    def zip_payload(payload: str) -> bytes:
        btsio = BytesIO()
        g = gzip.GzipFile(fileobj=btsio, mode='w')
        g.write(bytes(payload, 'utf8'))
        g.close()
        return btsio.getvalue()
    
    headers = {
        'Content-Encoding': 'gzip'
    }
    zipped_payload = zip_payload(payload)
    requests.post(url, zipped_payload, headers=headers)
    
    

提交回复
热议问题