2017-04-19 46 views
0

我在Python中使用requests来通过POST发送文件。 我的代码如下所示:通过POST发送文件而无需在Python中进行内容处理

headers = {'Content-Type': 'application/x-tar',       
      'Content-Length': tar_size} 

r = requests.post(server,        
        files={"file": (tar_name, open(tar_name, 'rb'))},   
        headers=headers) 

在从另一个客户端(C语言编写)的文件在同一台服务器都发送相同的方式。当body_file(的WebOb的东西在这里看到http://docs.webob.org/en/stable/api/request.html)被读取,从C客户端读取文件,但是从我在Python客户真正的文件prepened有:

--2a95cc93056b45e0b7c3447234788e29 
Content-Disposition: form-data; name="file"; filename="filename.tar" 

是否有某种方式来阻止我的客户发送这些东西?或者某种方式如何修复服务器,以便它可以从C客户端和我的客户端读取(尽管看起来我们发送了一些不同的消息)

+0

你的意思是你想发送的只是字节,没有别的? HTTP头怎么样? – Bemmu

+0

在我看来,多部分/表单数据编码确实需要“Content-Disposition”东西,因此C实现是不正确的,还是定义了自定义客户端和服务器之间的不同协议?更有用的信息在这里:http://stackoverflow.com/questions/8659808/how-does-http-file-upload-work – Bemmu

回答

0

好吧,我能解决这个问题。如果有人遇到同样的问题,我会在这里发布我的解决方案。

的解决方案是使用准备请求http://docs.python-requests.org/en/master/user/advanced/#prepared-requests) 然后,我可以把数据放到身体在我所需要的形式。我的代码现在看起来像这样:

headers = {'Content-Type': 'application/x-tar',       
      'Content-Size': tar_size} 

req = requests.Request('POST', 
         server, 
         headers)  

prepped = req.prepare() 
with open(tar_name, 'rb') as f: 
    prepped.body = fl.read(tar_size) 

s = Request.Session() 
r = s.send(prepped, 
      stream=True)