接口测试 python Requests 怎么才能让 post 的 json 经过 gzip 压缩之后再上传?

huiyu · August 22, 2017 · Last by liumeifang replied at March 05, 2018 · 3553 hits

我 post 的 json 非常大,如果不经过压缩,上传想要 40 秒,我想压缩之后再上传应该怎么弄?
头文件已经加入 了 ,'Content-Encoding': 'gzip','Accept-encoding': 'gzip'
没有用,如果先压缩 json 再传也会报错
如果 json 是被压缩的,那么
client.post(url='XXXX', json=json,headers=headers)
json 也不能上传

共收到 8 条回复 时间 点赞

把完整代码贴上来?

gzip 可不仅仅是加个 header 就表示用了 gzip 哦,实际的 http body 也需要真的用了 gzip 方法压缩才行。否则服务端一解压还是会出错。

另外,是否使用 gzip 需要客户端和服务端统一,只是其中一方使用是不行的。

json 数据比较大,可以考虑存在文件中,再发送。参考代码

files = {'upload_file': open('file.json','rb')}

r = requests.post(url, files=files, data=values)

或者

借助于第三方 requests 插件

import requests
from requests_toolbelt.multipart import encoder

session = requests.Session()
with open('my_file.csv', 'rb') as f:
    form = encoder.MultipartEncoder({
        "documents": ("my_file.csv", f, "application/octet-stream"),
        "composite": "NONE",
    })
    headers = {"Prefer": "respond-async", "Content-Type": form.content_type}
    resp = session.post(url, headers=headers, data=form)

以上没有试验,你可以自己试试看噢。

参考链接

deflate2 压缩,压缩比比较好,服务端给一个接口用来收数据,http 请求附带上压缩的 json 文件,到服务端解压重新拿数据请求原始 url

试试流式上传,
Requests 支持流式上传,这允许你发送大的数据流或文件而无需先把它们读入内存。要使用流式上传,仅需为你的请求体提供一个类文件对象即可:
with open('massive-body') as f:
requests.post('http://some.url/streamed', data=f)

问题解决了,
情况是我得用 data=json 才能上传,
上传前先对 json 压缩,上传压缩后的数据

Author only
huiyu #7 · March 05, 2018 Author
liumeifang 回复

data=str(data)
data=data.encode('utf-8')
data = gzip.compress(data)

非常感谢楼主!!

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up