带有上传文件的Python HTTP Post和Postman生成的标题

时间:2018-03-26 09:10:58

标签: python http-headers http-post postman

我正在使用Python 2.7

我想使用HTTP POST制作requests,我在其中上传文件和必须放在HTTP Headers中的密钥。

为此,我使用了应用程序Postman,它的工作原理非常好。 Postman example

Postman我只添加了必要的标题,这是一个带有一些键的Authorization。 在body上,我选择了form-data,然后键是input_image,它们就是图像本身。

现在我想将其复制到Python2.7,所以我选择在Postman上看到Python代码,就是这个:

import requests

url = "https://foo.com/bar/stuff"

payload = "------WebKitFormBoundary7MA4YDxkTrZu1gW\r\nContent-Disposition: form-data; name=\"input_image\"; filename=\"C:\\Test\\projs\\Supermarket\\doritos.jpeg\"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary7MA4YDxkTrZu1gW--"
headers = {
    'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YDxkTrZu1gW",
    'Authorization': "myAuthorizationKey",
    'Cache-Control': "no-cache",
    'Postman-Token': "0efwd6e8-051c-4ed5-8d6f-7b1bd135f4d5"
    }

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

print(response.text)

这根本行不通。它具有与使用Postman发送任何图像时相同的行为。看起来有效负载字符串没有正确发送。

问题:

Postman自动生成代码有什么问题,以便HTTP POST同时向image upload headerPython发送 logging.getLogger('parso.cache').disabled=True logging.getLogger('parso.cache.pickle').disabled=True

3 个答案:

答案 0 :(得分:1)

我认为Postman正在做一些我们并不知道的逻辑。但是包requests提供了上传图片的方式。

files = {'media': open('my_image.jpg', 'rb')}
r = requests.post(url, files=files, headers=hearders)

根据您要将图像发送到的服务器,参数名称,此代码可能需要稍作更改。

答案 1 :(得分:0)

这里唯一的技巧是您的代码应该与您在邮递员中发布请求的代码相同,无需添加额外的标头,您的投递请求应该看起来与在邮递员中的相同。 为此,我可以将文件更改为图像文件,然后将其发布到我的发布请求中。

    with open('grass-small.png', 'rb') as imageFile:
        imageStr = base64.urlsafe_b64encode(imageFile.read())
    files = {'document': ('grass-small.png', imageStr ), 'document_type':(None,'grass')}

答案 2 :(得分:0)

这对我有用

import requests

url = 'http://iizuka.cs.tsukuba.ac.jp/projects/colorization/web/'
files = {'file': ("my_img_path/myImage.jpeg", open('my_img_path/myImage.jpeg', 'rb'),'image/jpg')}

r = requests.post(url, files=files)
相关问题