python:requests,我如何 post MULTIPART/FORM-DATA 和传输大文件?

python:requests, how do I post MULTIPART/FORM-DATA and stream large file?

我需要 POST 一个 .wav 文件 MULTIPART/FORM-DATA。

到目前为止我的脚本是:

import requests
import json
import wave 

def get_binwave(filename):

    w = wave.open(filename, "rb")
    binary_data = w.readframes(w.getnframes())
    w.close()
    return binary_data


payload = {
    "operating_mode":"accurate",
    "model":{
       "name":"code"
    },
    "channels":{
        "first":{
            "format": "audio_format",
            "result_format": "lattice"
         }
     }
}

multiple_files = [
    ("json","application/json",json.dumps(payload)),
    ("first","audio/wave",str(get_binwave("c.wav")))]
r = requests.post("http://localhost:8080", files=multiple_files)

我面临两个问题:

  1. .wav 二进制文件太大,我想我需要流式传输它?

  2. 服务器期望边界为="xxx---------------xxx"。如何设置?

如何正确完成所有这些操作?

Requests 实际上不会流式传输 multipart/form-data 上传(但它很快就会登陆那里)。在那之前,从 PyPI 安装 requests-toolbelt。要使用它,您的脚本看起来像

import requests
import json
from requests_toolbelt.multipart import encoder


payload = {
    "operating_mode":"accurate",
    "model":{
       "name":"code"
    },
    "channels":{
        "first":{
            "format": "audio_format",
            "result_format": "lattice"
         }
     }
}

multiple_files = [
    ("json", "application/json", json.dumps(payload)),
    ("first", "audio/wave", open("c.wav", "rb"),
]
multipart_encoder = encoder.MultipartEncoder(
    fields=multiple_files,
    boundary="xxx---------------xxx",
)
r = requests.post("http://localhost:8080",
                  data=multipart_encoder,
                  headers={'Content-Type': multipart_encoder.content_type})

有关该库和 MultipartEncoder 的更多文档,请参阅 http://toolbelt.readthedocs.io/en/latest/uploading-data.html#streaming-multipart-data-encoder