Dropbox API v2 - 尝试使用files_upload()上传文件 - 抛出TypeError

时间:2016-12-22 14:58:14

标签: python-3.x dropbox dropbox-api

我一直在尝试使用python3中的files_upload()函数将简单文件上传到dropbox

即使尝试tutorial provided on Dropbox's site中的代码,我也会收到错误,但我不明白为什么。我在这里缺少什么?

这是我的代码:

import dropbox

dbx = dropbox.Dropbox("my_access_token")

data = "asd"

dbx.files_upload(data, '/file.txt')

以下是我尝试运行时收到的错误消息:

Traceback (most recent call last):
  File "dbox.py", line 7, in <module>
    dbx.files_upload(data, '/file.txt')
  File "/usr/local/lib/python3.4/dist-packages/dropbox/base.py", line 1225, in files_upload
    f,
  File "/usr/local/lib/python3.4/dist-packages/dropbox/dropbox.py", line 249, in request
    timeout=timeout)
  File "/usr/local/lib/python3.4/dist-packages/dropbox/dropbox.py", line 341, in request_json_string_with_retry
    timeout=timeout)
  File "/usr/local/lib/python3.4/dist-packages/dropbox/dropbox.py", line 385, in request_json_string
    type(request_binary))
TypeError: expected request_binary as binary type, got <class 'str'>

我尝试过不同的方式:

1

with open("/home/pi/Desktop/dbox/asd.txt", "rb") as f:
    dbx.files_upload(f, '/asd.txt', mute = True)

2

dbx.files_upload("hello", "")

第3

dbx.files_upload("hello", "/")

但我每次都会得到同样的错误。

1 个答案:

答案 0 :(得分:15)

this文档中,files_upload()的第一个参数似乎需要是bytes个对象。这意味着你接近:

with open("/home/pi/Desktop/dbox/asd.txt", "rb") as f:
    dbx.files_upload(f, '/asd.txt', mute = True)

请尝试此操作(f.read()返回bytes个对象):

with open("/home/pi/Desktop/dbox/asd.txt", "rb") as f:
    dbx.files_upload(f.read(), '/asd.txt', mute = True)

您也可以尝试传递data.encode(whatever_encoding)而不仅仅是data。我不确定为什么在你链接的教程中没有提到这个。