我正在尝试发布curl
看起来像这样的请求:
curl -X POST \
--header "Authorization: Bearer 48378438…" \
--header "X-Backtory-Storage-Id: 125653265" \
--form fileItems[0].fileToUpload=@"/path/to/file1.txt" \
--form fileItems[0].path="/path1/path2/" \
--form fileItems[0].replacing=true \
http://storage.backtory.com/files
我的代码是这样的:
upload_headers = {'Authorization':'Bearer' + ' ' + access_token, 'X-Backtory-Storage-Id':'48378438**********'}
upload_data = {'fileItems[0].fileToUpload': open('file.txt', 'rb'), 'fileItems[0].path': r'/path1/', 'fileItems[0].replacing': True}
upload_response = requests.post("http://storage.backtory.com/files", files=upload_data, headers=upload_headers)
print(upload_r)
但运行此代码后,我收到此错误:
Traceback (most recent call last):
File "backtory-test.py", line 27, in <module>
upload_r = requests.post("http://storage.backtory.com/files", files=upload_data, headers=upload_headers)
File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 112, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 494, in request
prep = self.prepare_request(req)
File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 437, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 308, in prepare
self.prepare_body(data, files, json)
File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 496, in prepare_body
(body, content_type) = self._encode_files(files, data)
File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 159, in _encode_files
fdata = fp.read()
AttributeError: 'bool' object has no attribute 'read'
我的代码的哪一部分是错误的?
答案 0 :(得分:0)
files
字典中的每个值必须是类似文件描述符的对象(即具有read
方法)或元组(见下文)。
True
既没有这样的方法(如错误所示),也没有元组。
所以
upload_data = {'fileItems[0].fileToUpload': open('file.txt', 'rb'),
'fileItems[0].path': r'/path1/',
'fileItems[0].replacing': True}
应该只是
upload_data = {'filename': open('file.txt', 'rb')}
另一个选择是提供元组作为值。这允许您设置一些选项。您可以在requests
docs上阅读更多内容。
path
和replacing
听起来像是应该作为数据发布的变量,而不是files
字典的一部分。