【问题标题】:Sending authenticated multipart/form-data request using Python Requests使用 Python 请求发送经过身份验证的多部分/表单数据请求
【发布时间】:2016-08-18 03:30:12
【问题描述】:

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

这是我使用的代码:

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,我可以做些什么不同的事情?

【问题讨论】:

标签: python spring python-requests


【解决方案1】:

最后,我从来没有用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2011-11-01
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多