python - 如何在Python中使用requests上传文件

标签 python python-3.x python-requests

我尝试通过 Python 请求上传文件,但收到错误代码 400(错误请求)

#Update ticket with upload of CSV file
header_upload_file = {
            'Authorization': 'TOKEN id="' + token + '"',
            'Content-Type': 'multipart/form-data'
}

files = {
            'name': 'file',
            'filename': open(main_path + '/temp/test.txt', 'rb'),
            'Content-Disposition': 'form-data'
        }


response = requests.post(baseurl + '/incidents/number/' + ticket_number + '/attachments/', headers=header_upload_file, data=files, verify=certificate)

如果我通过 Postman 尝试,使用以下代码会成功。

url = "https://<url>"
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"C:\\Users\\<filename>\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
'Authorization': "TOKEN id="3e9d095d-a47b-48b5-a0b8-ae8b8ad9ae74"",
'cache-control': "no-cache",
'Postman-Token': "bb155176-b1b8-47a6-8fb3-46f5740cf9e0"
}

response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)

我做错了什么?

最佳答案

您应该使用files 参数。另外,不要在 header 中显式设置 Content-Type,以便 requests 可以为您设置适当的边界:

header_upload_file = {
    'Authorization': 'TOKEN id="' + token + '"'
}
response = requests.post(
    baseurl + '/incidents/number/' + ticket_number + '/attachments/',
    headers=header_upload_file,
    files={'file': ('file', open(main_path + '/temp/test.txt', 'rb'), 'text/csv')},
    verify=certificate
)

关于python - 如何在Python中使用requests上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653331/

相关文章:

python - X 标签 matplotlib

python - 修改 tk.Button 上的部分文本

python 3 : Write to File from Cursor Based List

python - Pytest 补丁字段的继承 django 模型的默认属性

python - 可以通过自定义 SQLObject Select 调用获取生成器吗?

python - 在 Python 中访问嵌套的 JSON 元素

python - 在 Python 中获取 MP3 文件句柄的长度

excel - 将多个 csv 文件合并到一个 xls 工作簿 Python 3

python - 尝试在 Python 3 上安装 pygame 时出错

python - 如何获取请求 'get' 来遵循所有重定向