Dropbox API - 尝试上传文件

时间:2018-04-25 18:59:32

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

我刚刚重建了我的Raspberry Pi,因此安装了最新版本的Dropbox API,现在我的程序无法运行。我认为这是由于这些重大变化中的第1点:https://github.com/dropbox/dropbox-sdk-python/releases/tag/v7.1.0。我确信SO(Dropbox API v2 - trying to upload file with files_upload() - throws TypeError)这个问题解决了我的问题...但作为一个新手,我无法弄清楚如何实际实现它 - 无论如何,我是已经使用f.read() ...有人可以帮忙吗?

这是我的代码:

def DropboxUpload(file):
    sourcefile = "/home/pi/Documents/iot_pm2/dropbox_transfer/" + filename
    targetfile = "/" + filename
    dbx = dropbox.Dropbox(cfg.dropboxtoken)
    f = open(sourcefile, "r")
    filecontents = f.read()
    try:
        dbx.files_upload(filecontents, targetfile, mode=dropbox.files.WriteMode.overwrite)
    except dropbox.exceptions.ApiError as err:
        print(err)
    f.close()

这就是错误:

Traceback (most recent call last):
  File "/home/pi/Documents/iot_pm2/dropbox_uploader.py", line 20, in <module>
    DropboxUpload(filename)
  File "/home/pi/Documents/iot_pm2/dropbox_uploader.py", line 12, in DropboxUpload
    dbx.files_upload(filecontents, targetfile, mode=dropbox.files.WriteMode.overwrite)
  File "/usr/local/lib/python3.5/dist-packages/dropbox/base.py", line 2125, in files_upload
    f,
  File "/usr/local/lib/python3.5/dist-packages/dropbox/dropbox.py", line 272, in request
    timeout=timeout)
  File "/usr/local/lib/python3.5/dist-packages/dropbox/dropbox.py", line 363, in request_json_string_with_retry
    timeout=timeout)
  File "/usr/local/lib/python3.5/dist-packages/dropbox/dropbox.py", line 407, in request_json_string
    type(request_binary))
TypeError: expected request_binary as binary type, got <class 'str'>

提前致谢。

1 个答案:

答案 0 :(得分:1)

您需要提供bytes,但您提供str

您可以通过将文件模式更改为二进制来获取bytes。即,而不是:

f = open(sourcefile, "r")

做的:

f = open(sourcefile, "rb")