简体   繁体   English

python:requests,如何发布MULTIPART / FORM-DATA并传输大文件?

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

I need to POST a .wav file in MULTIPART/FORM-DATA. 我需要在MULTIPART / FORM-DATA中发布.wav文件。

my script so far is : 到目前为止,我的脚本是:

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)

I'm facing two problems: 我面临两个问题:

  1. The .wav file binary is too big, so I'm guessing I need to stream it? .wav文件二进制文件太大,因此我猜我需要对其进行流传输?

  2. The the server expects the boundary to be = "xxx---------------xxx". 服务器期望边界为=“ xxx --------------- xxx”。 How do I set it ? 如何设置?

How do I do all of this properly? 如何正确处理所有这些?

Requests does not actually stream multipart/form-data uploads (but it will be landing there soon). 请求实际上并没有流式传输multipart/form-data上载(但是它将很快到达那里)。 Until then, install requests-toolbelt from PyPI. 在此之前, requests-toolbelt从PyPI安装requests-toolbelt To use it, your script would look like 要使用它,您的脚本看起来像

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

For more documentation about that library and the MultipartEncoder, see http://toolbelt.readthedocs.io/en/latest/uploading-data.html#streaming-multipart-data-encoder 有关该库和MultipartEncoder的更多文档,请参见http://toolbelt.readthedocs.io/en/latest/uploading-data.html#streaming-multipart-data-encoder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM