Python:POST一个多部分编码的文件

时间:2016-10-20 20:54:51

标签: python-requests postman

尝试使用请求模块上传文件,但遇到内部服务器错误使用海报模块也是如此:

import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
files={'file': open(r'Users/.../test.zip', 'rb')}
headers_info = {
    'content-type': "multipart/form-data; boundary=---12345",
    'x-api-service-version': "1.0",
    'connection': "Keep-Alive",
    'authorization': "Basic XXXXXXX",
    'x-file-format': "decrypted",
    'cache-control': "no-cache",
    }

response = requests.post(url, data = payload , headers=headers_info , params=querystring , files=files)

print response.status_code
print response.text

我用POSTMAN测试了api(镀铬扩展来测试其余的API),它似乎与邮递员一起正常工作我得到了成功的回复并且上传了文件。

python的邮递员代码显示:

import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
headers = {
    'content-type': "multipart/form-data; boundary=---12345",
    'accept-encoding': "gzip, deflate",
    'x-api-service-version': "1.0",
    'connection': "Keep-Alive",
    'authorization': "Basic XXXXXXX",
    'x-file-format': "decrypted",
    'cache-control': "no-cache",
    'postman-token': "XXXXXXX"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)

对此有何建议?我错过了一些明显的东西吗感谢您分享的任何指示!

1 个答案:

答案 0 :(得分:1)

您不必指定'content-type': "multipart/form-data; boundary=---12345",以及空data。尝试在没有headers

的情况下发送请求
response = requests.post(url, params=querystring , files=files)

如果您失败,可能会尝试添加'authorization': "Basic XXXXXXX", 'postman-token': "XXXXXXX"标题