【问题标题】:Python HTTP Post with upload file and headers generated from Postman带有从 Postman 生成的上传文件和标头的 Python HTTP Post
【发布时间】:2018-09-04 09:07:56
【问题描述】:

我正在使用Python 2.7。

我想使用requests 创建一个HTTP POST,我上传一个文件和一个必须放在HTTP Headers 中的密钥。

为此,我使用了应用程序Postman,它工作得非常好。

在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 发送任何图像一样。看起来负载字符串没有正确发送。

问题:

为了在Python 中同时发送HTTP POST 和image upload 和header,这个Postman 自动生成代码有什么问题?

【问题讨论】:

    标签: python http-headers http-post postman


    【解决方案1】:

    这对我有用

    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)
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

        • 嗨@Jrmyy 谢谢。但显然 Web API 也请求了我也放在上面的有效负载。有什么办法也可以使用吗?如果我只使用 as data=payload,它会抱怨负载不能是字符串。
        • @waas1919,如果您需要放置有效载荷,也许类似的方法可以工作:with open('my_image.jpg', "rb") as image_file: payload = base64.b64encode(image_file.read()) 然后您可以使用有效载荷,因为它将是字节(如果您愿意,可以尝试将您在示例中的有效负载转换为字节)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-16
        • 2013-08-03
        相关资源
        最近更新 更多