2016-04-24 110 views
0

使用Python和请求,我试图使用带有自定义身份验证机制的multipart/form-data POST请求将文件上传到API(只需添加一个'Authentication-Token 'header)。使用Python请求发送经过身份验证的多部分/表单数据请求

这里是我使用的代码:

import requests 
from requests.auth import AuthBase 

class MyAuth(AuthBase): 

    def __init__(self, token): 
     self.token = token 

    def __call__(self, r): 
     r.headers['Authentication-Token'] = self.token 
     return r 

token = "175a5607d2e79109539b490f0f8ffe60" 
url = "https://my-ap.com/files" 

r = requests.post(url, 
        files={'file': open('qsmflkj.jpg', 'rb')}, 
        data={'id': 151}, 
        auth=MyAuth(token) 
) 

不幸的是,这个请求会导致服务器上的以下异常(后端使用Spring框架):

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found 

我已经尝试了很多事情,比如自己添加头文件,但这似乎是“正确”的方式,并且它失败了。我知道API是从各种移动客户端使用的,因此可以在那里上传图片。我能做些什么不同的事情才能够在Python中使用这个API?

+1

我觉得春天是问题http://stackoverflow.com/a/28303489/2141635 –

回答

0

最后,我从来没有设法与要求这样做,但我成功地用的urllib2和海报库:

from poster.encode import multipart_encode 
from poster.streaminghttp import register_openers 

import urllib2 

register_openers() 
token = "175a5607d2e79109539b490f0f8ffe60" 

with open('qsmflkj.jpg', 'rb') as f: 
    datagen, headers = multipart_encode({"file": f}) 
    headers['Authentication-Token'] = token 
    request = urllib2.Request("https://myserver.com/files", \ 
           datagen, headers) 
    response = urllib2.urlopen(request)