【发布时间】:2015-06-10 09:53:27
【问题描述】:
我是编程和学习python的新手,所以请多多包涵,感谢您的帮助....
我正在做一个项目,我需要将文件上传到存储服务,我目前正在尝试使用 box API。我正在尝试使用此页面上的代码:
how to use python's Request library to make an API call with an attachment and a parameter
import requests
import json
#the user access token
access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
#the name of the file as you want it to appear in box
filename = 'box_file'
#the actual file path
src_file = "C:\Python\Wildlife.wmv"
#the id of the folder you want to upload to
parent_id = '0'
headers = { 'Authorization: Bearer {0}'.format(access_token)}
url = 'https://upload.box.com/api/2.0/files/content'
files = { 'filename': (filename, open(src_file,'rb')) }
data = { "parent_id": parent_id }
response = requests.post(url, data, files, headers)
file_info = response.json()
我尝试了许多不同的东西,但实际上并没有让我更接近,所以我发布了我对他们代码的轻微改编。目前我收到此错误:
Traceback (most recent call last):
File "transfer2.py", line 18, in <module>
response = requests.post(url, data, files, headers)
TypeError: post() takes from 1 to 3 positional arguments but 4 were given
我在其他一些实验中也遇到了 file_info = response.json()" 的问题。如果有人可以帮助我完成这项工作,我将不胜感激。
如果有帮助,我正在使用 python 3。
编辑 4/6 根据要求,我更改了这一行: response = requests.post(url, data=data, files=files, headers=headers)
这是我现在得到的错误:
Traceback (most recent call last):
File "transfer2.py", line 18, in <module>
response = requests.post(url, data=data, files=files, headers=headers)
File "C:\Python34\lib\site-packages\requests\api.py", line 108, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Python34\lib\site-packages\requests\api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 450, in request
prep = self.prepare_request(req)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 381, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "C:\Python34\lib\site-packages\requests\models.py", line 305, in prepare
self.prepare_headers(headers)
File "C:\Python34\lib\site-packages\requests\models.py", line 410, in prepare_headers
self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
AttributeError: 'set' object has no attribute 'items'
【问题讨论】:
-
还有一个新的Box Python SDK,它可能会使 API 的使用更容易一些。有一个如何上传文件here的示例。
-
Greg,是否可以使用SDK上传指定目录下的所有文件?
-
我认为没有。您需要遍历文件夹中的文件并分别上传每个文件。如果您有其他特定于 Python SDK 的问题,我建议您发布一个单独的问题。
标签: python python-3.x box-api boxapiv2