pythonpython-2.7dropboxdropbox-api

Dropbox Python API: Uploading a file


I would like to know how to use the dropbox library in Python 2.7 to upload a file to my Dropbox.

I have successfully connected to my Dropbox and the Dropbox object is called db.

How to do this?


Solution

  • The Dropbox Python SDK provides both API v1 and API v2 functionality for backwards compatibility, but only API v2 should be used now, as API v1 is deprecated. The tutorial covers the basic of using the API v2 functionality.



    This uses the Dropbox Python SDK to download a file from the Dropbox API at the remote path /Homework/math/Prime_Numbers.txt to the local file Prime_Numbers.txt:

    import dropbox
    dbx = dropbox.Dropbox("<ACCESS_TOKEN>")
    
    with open("Prime_Numbers.txt", "wb") as f:
        metadata, res = dbx.files_download(path="/Homework/math/Prime_Numbers.txt")
        f.write(res.content)
    

    <ACCESS_TOKEN> should be replaced with your access token.



    And for uploading:

    This uses the Dropbox Python SDK to upload a file to the Dropbox API from the local file as specified by file_path to the remote path as specified by dest_path. It also chooses whether or not to use an upload session based on the size of the file:

    f = open(file_path)
    file_size = os.path.getsize(file_path)
    
    CHUNK_SIZE = 4 * 1024 * 1024
    
    if file_size <= CHUNK_SIZE:
    
        print dbx.files_upload(f.read(), dest_path)
    
    else:
    
        upload_session_start_result = dbx.files_upload_session_start(f.read(CHUNK_SIZE))
        cursor = dropbox.files.UploadSessionCursor(session_id=upload_session_start_result.session_id,
                                                   offset=f.tell())
        commit = dropbox.files.CommitInfo(path=dest_path)
    
        while f.tell() < file_size:
            if ((file_size - f.tell()) <= CHUNK_SIZE):
                print dbx.files_upload_session_finish(f.read(CHUNK_SIZE),
                                                cursor,
                                                commit)
            else:
                dbx.files_upload_session_append(f.read(CHUNK_SIZE),
                                                cursor.session_id,
                                                cursor.offset)
                cursor.offset = f.tell()
    
    f.close()