gpt4 book ai didi

Python 请求 - 使用 multipart/form-data 发布一个 zip 文件

转载 作者:太空狗 更新时间:2023-10-30 00:36:26 24 4
gpt4 key购买 nike

我正在玩弄 Python Requests 模块,到目前为止它一直很令人愉快。

但是,我在尝试使用 multipart/form-data 发布 zip 文件时遇到了问题。

我正在使用 Digest 身份验证并且能够成功发布其他文件类型,例如.xls 等

我正在使用以下方式创建发布请求:

file = open('/Users/.../test.zip', 'rb').read()
r = requests.post(url, auth=HTTPDigestAuth('dev', 'dev'), data = {"mysubmit":"Go"}, files={"archive": ("test.zip", file)})

这会出错并给出:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='10.2.2.70', port=80): Max retries exceeded with url: /plugin_install 
(Caused by <class 'socket.error'>: [Errno 32] Broken pipe)

我尝试使用较小的 zip 文件并更改数据/文件值,但出现了同样的错误。

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

感谢您提供的任何光线!

最佳答案

请求而言,zip 文件与任何其他二进制数据 block 之间没有区别

你的服务器在这里坏了;当您向它发送 zip 文件时,它正在切断连接。 requests 对此无能为力。

当您遇到这些问题时,您可能想针对 http://httpbin.org/ 进行测试;它是由 requests 库的作者构建的测试服务。

另一个提示:发送时不需要将整个文件对象读入内存。只需将对象本身传递给 requests 即可:

fileobj = open('/Users/.../test.zip', 'rb')
r = requests.post(url, auth=HTTPDigestAuth('dev', 'dev'), data = {"mysubmit":"Go"}, files={"archive": ("test.zip", fileobj)})

针对 httpbin.org 的演示:

>>> import requests
>>> fileobj = open('/tmp/test.zip', 'rb')
>>> r = requests.post('http://httpbin.org/post', data={"mysubmit":"Go"}, files={"archive": ("test.zip", fileobj)})
>>> r
<Response [200]>
>>> r.json()
{u'origin': u'217.32.203.188', u'files': {u'archive': u'data:application/zip;base64,<long base64 body omitted>'}, u'form': {u'mysubmit': u'Go'}, u'url': u'http://httpbin.org/post', u'args': {}, u'headers': {u'Content-Length': u'57008', u'Accept-Encoding': u'gzip, deflate, compress', u'Connection': u'close', u'Accept': u'*/*', u'User-Agent': u'python-requests/1.2.3 CPython/2.7.5 Darwin/12.4.0', u'Host': u'httpbin.org', u'Content-Type': u'multipart/form-data; boundary=9aec1d03a1794177a38b48416dd4c811'}, u'json': None, u'data': u''}

关于Python 请求 - 使用 multipart/form-data 发布一个 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18208109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com