【问题标题】:Python Requests - Uploading a Zip filePython 请求 - 上传 Zip 文件
【发布时间】:2019-05-12 14:00:19
【问题描述】:

我有一个需要上传的 zip 文件。当我使用 CURL 命令时,它正在上传它,但是当我使用 Python 请求尝试相同时,我得到HTTP 405 Method Not Allowed。 zip 文件通常在 500kb 左右。

卷曲命令 -

curl -u<username>:<password> -T /log/system/check/index.zip "<target URL>"

Python 脚本(尝试了 2 种不同的方法) -

1:

import requests
files = {'file': open('/log/system/check/index.zip', 'rb')}
r = requests.post(url, files=files, auth=('<username>', '<password>'))

2:

import requests
fileobj = open('/log/system/check/index.zip', 'rb')
r = requests.post(url, auth=('<username>', '<password>'), files={"archive": ("index.zip", fileobj)})

我是否遗漏了一些明显的东西?

【问题讨论】:

  • 那么curl 命令成功了吗? curl 联机帮助页说明了 -TIf this is used on an HTTP(S) server, the PUT command will be used. 因此,curl 使用的是 PUT,而不是 POST。您的端点是否允许POST
  • 我现在尝试使用 PUT 并看到错误 - Tunnel connection failed: 503 Service Unavailable',不确定是否需要任何代理
  • 但为了清楚起见,您列出的 curl 命令可以正常工作吗?
  • 是的,它工作得非常好。它正在上传文件。

标签: python curl python-requests


【解决方案1】:

也许这会对你有所帮助。

 with open(zipname, 'rb') as f:
uploadbase = requests.put('url',
                    auth=(base, pwd),
                    data=f,
                    headers={'X-File-Name' : zipname, 
                                  'Content-Disposition': 'form-data; name="{0}"; filename="{0}"'.format(zipname), 
                                   'content-type': 'multipart/form-data'})

the difference between put and post

【讨论】:

  • 谢谢拯救我的一天
【解决方案2】:

curl -T ... 使用 PUT 方法而不是 POST。 正如错误消息所说,您应该使用

r = requests.put(url, ...)

【讨论】:

  • 我现在尝试使用 PUT 并看到错误 - Tunnel connection failed: 503 Service Unavailable',不确定是否需要任何代理,我是否遗漏了什么?
猜你喜欢
  • 2017-10-11
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
相关资源
最近更新 更多