簡體   English   中英

使用Python請求發送經過身份驗證的multipart / form-data請求

[英]Sending authenticated multipart/form-data request using 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,我可以做些什么?

最后,我從未設法用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM