Python:将包含附加字段的文件块上传到服务器

Python:将包含附加字段的文件块上传到服务器,python,http,post,python-requests,pycurl,Python,Http,Post,Python Requests,Pycurl,我在这里原谅自己。。。我是一个无赖。。。但我需要创建一个python脚本,它获取一个文件并将其分块上传到服务器,包括额外的数据 编辑:我只想上传一个文件。。。但是成块的 所以我开始研究,发现了pycurl,这似乎很复杂。所以我接着讨论了请求,它看起来非常好而且直观 基本上我把它分成了几个部分。。。但是并不是所有这些加起来:) 我发现我可以使用生成器来提供数据块。太棒了!但我也需要发送(对不起…我的词汇,当它涉及到这类东西是非常有限的)多部分边界???包含JSON信息的其他字段 所以我的请求应该是

我在这里原谅自己。。。我是一个无赖。。。但我需要创建一个python脚本,它获取一个文件并将其分块上传到服务器,包括额外的数据

编辑:我只想上传一个文件。。。但是成块的

所以我开始研究,发现了
pycurl
,这似乎很复杂。所以我接着讨论了
请求
,它看起来非常好而且直观

基本上我把它分成了几个部分。。。但是并不是所有这些加起来:)

我发现我可以使用生成器来提供数据块。太棒了!但我也需要发送(对不起…我的词汇,当它涉及到这类东西是非常有限的)多部分边界???包含JSON信息的其他字段

所以我的请求应该是这样的:

POST / HTTP/1.1
Host: some server
Content-Type: multipart/form-data;

Connection: Keep Alive
Transfer-Encoding: chunked

--boundary
Content-Disposition: form-data; name="Name of my field"
Content-Type: application/JSON; charset=utf-8
Content-Transfer-Encoding: 8bit

{"Some" : "content", "in" : "here"}

--boundary
Content-Disposition: form-data; name="My File"
Content-Type: audio/mpeg
Content-Transfer-Encoding: binary

... chunk 1 ....

--boundary
Content-Disposition: form-data; name="My File"
Content-Type: audio/mpeg
Content-Transfer-Encoding: binary

... chunk 2 ....

and so on...
我想我可以使用生成器创建分块上传。我还发现我可以使用
file=
选项创建非文件边界

但问题是我不能同时使用这两种语言:(而且在使用我的generator时,我不能定义块的
内容类型,也不能定义名称

再一次…抱歉我的词汇量不好:)


非常感谢您的帮助

我真的不知道这对我有什么帮助?因为在您的示例中,
doc.txt
doc2.html
的内容没有分块上传。。。我想定义这些文件的每个字节应该有多少字节。。。
import requests
import json

#from here http://stackoverflow.com/a/23816211/642096
def pretty_print_POST(req):
    """
    At this point it is completely built and ready
    to be fired; it is "prepared".

    However pay attention at the formatting used in 
    this function because it is programmed to be pretty 
    printed and may differ from the actual request.
    """
    print('{}\n{}\n{}\n\n{}'.format(
        '-----------START-----------',
        req.method + ' ' + req.url,
        '\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
        req.body,
    ))

url = 'http://httpbin.org/post'
data = {'input_name': json.dumps({
    'json': 'here'
})}
files = {
    'file1': ('doc.txt', open('/tmp/doc.txt', 'rb'), 'text/plain'),
    'file2': ('doc2.html', open('/tmp/doc2.html', 'rb'), 'text/html'),    
}
r = requests.post(url, data=data, files=files)
pretty_print_POST(r.request)
print r.text