使用Python请求发送经过身份验证的multipart / form-data请求

时间:2016-04-24 20:49:05

标签: python spring python-requests

使用Python和Requests,我尝试使用带有自定义身份验证机制的multipart / form-data POST请求将文件上传到API(只需添加'Authentication-Token'标头)。

以下是我使用的代码:

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 个答案:

答案 0 :(得分:0)

最后,我从未设法用Requests做到这一点,但我成功地使用了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)