【问题标题】:How can I use the equivalent of "curl -T "myfile" "url"如何使用等效的“curl -T”myfile“url”
【发布时间】:2019-11-15 07:15:18
【问题描述】:

我需要将本地图片上传到 URL。 我的 curl 请求看起来像:“curl -T 'my_picture' 'the_url'”。

我的目的是在 Python 中完成,我看到了,我必须使用:requests.put()。 我之前所做的一切都很好,但是这个功能给我带来了很多麻烦。

解决方案可能真的很简单,但我迷路了。

感谢您的帮助。

def apithree(urlupload):
    url = urlupload
    picture = Image.open("test.png")
    headers = {"content-type": "multipart/form-data"}

    response = requests.put(url, headers=headers, data=picture)
    response = response.json()
    print(response)

我尝试过的其他代码

def apithree(urlupload):
    url = urlupload
    files = {'image': open('test.png', 'rb')}

    response = requests.post(url, data=files)
    response = response.json()
    print(response)

如果命令有效,输出应该是空的,但我总是有错误消息。

如有必要,我可以添加错误消息。

感谢您的帮助。

【问题讨论】:

    标签: python-3.x api python-requests


    【解决方案1】:

    如果服务器接受multipart/form-data 图像,您可能需要files= parameter 来满足您的请求:

    import requests
    
    files = {'file_name': open(r'C:\data\...\image.png', 'rb')}
    r = requests.post(YOUR_URL, files=files)  # or requests.put(...)
    print(r.status_code, r.json())
    

    【讨论】:

    • 感谢您的回答。我试过这个,但我有这个错误消息: requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection must have been closed by the remote host', None, 10054, None))
    • curlrequests 中的 URL 是否相同?他们在使用 https 吗?
    • 尝试再次运行此代码。如果它仍然给您 10054 错误,请检查您是否可以向此 URL 发出任何其他请求(例如使用 requestscurl 获取)。
    • 是的,这是同一个 URL,我打印了我的 url,然后我自己尝试了 Curl,它可以工作。对于第二点,我还在每个部分中添加了“time.sleep(2)”,以同时生成更少的请求,但仍然是这个错误。我将尝试以另一种格式对 curl 提出我的请求,希望它能起作用。如果我发现了什么,我会发布它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2013-06-20
    • 1970-01-01
    • 2014-01-25
    • 2013-05-19
    • 2016-01-09
    相关资源
    最近更新 更多