Python post提交gzip的方式

# 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)

 

I've tested the solution proposed by Robᵩ with some modifications and it works.

 

PSEUDOCODE (sorry I've extrapolated it from my code so I had to cut out some parts and haven't tested, anyway you can get your idea)

 

additional_headers['content-encoding'] = 'gzip'

s = StringIO.StringIO()

g = gzip.GzipFile(fileobj=s, mode='w')

g.write(json_body)

g.close()

gzipped_body = s.getvalue()

request_body = gzipped_body

 

r = requests.post(endpoint_url, data=request_body, headers=additional_headers)

 

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)

 

Tags:Python Http Gzip Deflate

Related

 

Python+OpenCV: cv2.imwrite

Python MemoryError: cannot allocate array memory

PDF Box generating blank images due to JBIG2 Images in it

Recommended size of icon for Google Chrome Extension

canvas.toDataURL() SecurityError

I get "The build could not read 1 project" in maven build because undefined versions

How do I know python path on linux ubuntu?

parser error : Start tag expected, '<' not found

Find out your own license number in Visual Studio 2010

Mocking using Moq in c#

Run a .cmd file through PowerShell

Lua - convert string to table

Recent Posts

Pandas how to find column contains a certain value

Recommended way to install multiple Python versions on Ubuntu 20.04

Build super fast web scraper with Python x100 than BeautifulSoup

How to convert a SQL query result to a Pandas DataFrame in Python

How to write a Pandas DataFrame to a .csv file in Python

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值