【问题标题】:equivalent python requests call to CURL request to upload image等效python请求调用CURL请求上传图片
【发布时间】:2014-03-26 17:56:22
【问题描述】:

我正在使用 Python requests 模块,但无论我尝试上传图片,它都会成功,但图片在打开/读取时出错。 我将图像编码为 base64,设置内容类型标题(图像/png、图像/jpeg 等...)等...

无论如何,我使用 CURL 执行以下操作并且它有效:

curl -u test@test.ca:test -H 'Content-Type: image/jpeg' --data-binary @test.jpeg -X POST 'https://test.test.com/api/upload.json?filename=test.jpeg'

这个请求与 python 中的 requests 模块(标头等)的等价物是什么?

【问题讨论】:

    标签: python curl python-requests


    【解决方案1】:

    要重现您的curl 命令,您不需要在base64 中编码图像:--data-binary @test.jpeg curl 选项按原样发送test.jpeg 文件:

    import requests
    
    r = requests.post('https://example.com/api/upload.json?filename=test.jpeg', 
                      data=open('test.jpeg', 'rb'), 
                      headers={'Content-Type': 'image/jpeg'},
                      auth=('test@test.ca', 'test')) # username, password
    

    【讨论】:

    • 这个工作,因为我改变而不是使用 files={'file.png':etc...} 到 data=etc.. 代替。谢谢。
    • ...我正要切换到 urrlib2,我有一个可行的实现。
    【解决方案2】:
    headers = {'Content-Type' : 'image/jpeg'}
    params = {'filename' : 'test.jpg'}
    r = requests.post("https://test.test.com/api/upload.json",
                       auth=('user','pw'), headers=headers, params=params)
    

    【讨论】:

    • 文件 ={'test.png':base64.b64encode(open('test.png', 'r').read())}
    • 我已经在做这种类型的请求了。感谢您的回复。我需要将它包含在文件中。它会工作,但在上传后无法打开/读取图像。但适用于 CURL
    猜你喜欢
    • 2016-11-08
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多