我需要在MULTIPART / FORM-DATA中发布.wav文件。
到目前为止,我的脚本是: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)
我面临两个问题:
.wav文件二进制文件太大了,所以我猜我需要传输它吗?
服务器期望边界为=" xxx --------------- xxx"。我该如何设置?
如何正确完成所有这些?
答案 0 :(得分:0)
请求实际上并未传输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