Dropbox API - 正在尝试上传文件

Dropbox API - trying to upload a file

我刚刚重建了我的 Raspberry Pi,因此安装了最新版本的 Dropbox API,但现在我的程序无法运行。我认为这是由于这些重大更改中的第 1 点:https://github.com/dropbox/dropbox-sdk-python/releases/tag/v7.1.0. I'm sure this question from SO () 解决了我的问题......但作为新手,我无法弄清楚如何实际实施它 - 无论如何,我已经在使用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'>

提前致谢。

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

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

f = open(sourcefile, "r")

做:

f = open(sourcefile, "rb")