使用 requests lib PUT 二进制数据
我需要创建一个小型 WebDAV 客户端,仅在服务器上上传文件。
我发现“请求”库似乎很容易使用,但我无法正确使用它。
客户端应该传输二进制文件 - 所以我使用了下面的示例:
>>> url = 'http://IPADDR/webdav'
>>> files = {'report.xls': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
来自 http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file。
对我来说它不起作用,我有以下错误:
File ".../site-packages/requests/packages/urllib3/connectionpool.py", line 260, in _make_request
conn.request(method, url, **httplib_request_kw)
File ".../httplib.py", line 941, in request
self._send_request(method, url, body, headers)
File ".../httplib.py", line 975, in _send_request
self.endheaders(body)
File ".../httplib.py", line 937, in endheaders
self._send_output(message_body)
File ".../httplib.py", line 795, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 147: ordinal not in range(128)
输入文件应该以某种方式编码吗? (我在“请求”文档中没有找到任何相关内容)。
I need to create a small WebDAV client that just upload files on the server.
I've found "requests" library that seems to be very easy to be used but I'm not able to use it properly.
The client should transfer binary files - so I've used the example bellow:
>>> url = 'http://IPADDR/webdav'
>>> files = {'report.xls': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
from http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file.
For me it's not working, I have the following error:
File ".../site-packages/requests/packages/urllib3/connectionpool.py", line 260, in _make_request
conn.request(method, url, **httplib_request_kw)
File ".../httplib.py", line 941, in request
self._send_request(method, url, body, headers)
File ".../httplib.py", line 975, in _send_request
self.endheaders(body)
File ".../httplib.py", line 937, in endheaders
self._send_output(message_body)
File ".../httplib.py", line 795, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 147: ordinal not in range(128)
Should be the input file somehow encoded? (I didn't found anything related in the "requests" documentation).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过一些调试,我实际上发现了发生了什么。
我能够通过删除脚本中的以下导入来解决此问题:
此导入似乎会导致 不需要的字符串urllib3 中的转换(请求所依赖的)。
正如请求作者所解释的,此问题应针对urllib3。
After some debugging, I've actually found what's happening.
I was able to fix the issue by removing the following import in my script:
This import seems to cause unwanted string conversions in urllib3 (which requests relies on).
As requests' author explained, this issue should be filed against urllib3.