Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropbox API v2 - trying to upload file with files_upload() - throws TypeError

I have been trying to upload a simple file to dropbox using the files_upload() function in python3

Even trying out the code in the tutorial provided on Dropbox's site I get an error and I don't understand why. What am I missing here?

Here is my code:

import dropbox

dbx = dropbox.Dropbox("my_access_token")

data = "asd"

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

And here is the error message I get when I try to run it:

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'>

I've tried it different ways:

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", "/")

but I get the same error every time.

like image 278
gasparrobi Avatar asked Dec 22 '16 14:12

gasparrobi


1 Answers

From this documentation, it appears that the first argument to files_upload() needs to be a bytes object. Which means you got close with:

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

Try this instead (f.read() returns a bytes object):

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

You could also try passing data.encode(whatever_encoding) instead of just data. I am not sure why this is not mentioned in the tutorial that you linked.

like image 99
elethan Avatar answered Oct 22 '22 01:10

elethan