无法使用python3请求发送带有文件的正确发布请求

时间:2020-04-01 13:00:40

标签: python-3.x api file-upload python-requests multipartform-data

我正在使用邮递员来发送帖子请求,如屏幕截图所示

screen from postman with successful request

现在我需要在python中实现它。这就是我现在所拥有的:

import requests

data = {"sendRequest": {"apiKey": 12345, "field1": "field1value"}}
files = {"attachment": ("file.txt", open("file.txt", "rb"))}
headers = {"Content-type": "multipart/form-data"}
response = requests.post(endpoint, data=data, headers=headers, files=files)

但仍然无法正常工作-服务器未将其接受为有效请求。我尝试了更多组合,但没有任何结果,而且我真的找不到解决方案。 我需要这一要求与邮递员中的要求完全一样

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案。我使用了来自request_toolbelt库的MultipartEncoder。

from requests_toolbelt import MultipartEncoder
import requests
import json

data = {"apiKey": 12345, "field1": "field1value"}}
mp = MultipartEncoder(
    fields={
        'sendRequest': json.dumps(data), # it is important to convert dict into json
        'attachment': ('file.pdf', open('file.pdf', 'rb'), 'multipart/form-data'),
    }
)
r = requests.post(ENDPOINT, data=mp, headers={'Content-Type': mp.content_type})