tedioustortoise
tedioustortoise

Reputation: 269

Python - uploading a zip folder to dropbox via APIv2 keeps failing

I am trying to upload a zip folder to dropbox. The zip is a backup, with a custom name according to the current date time. The folder is correctly zipped, named and stored. Sadly, there is always an issue uploading to dropbox. I have tested a readme.txt using the same code, which works. I don’t understand where this is going wrong. Thanks for any help.

import dropbox
import os
import datetime

dt = ('{:%Y%m%d_%H%M}'.format(datetime.datetime.now()))
name = dt + "_pa.zip"

os.system("zip -r " + name +  " /home/obliss")

class TransferData:
    def __init__(self, access_token):
        self.access_token = access_token
    def upload_file(self, file_from, file_to):
        dbx = dropbox.Dropbox(self.access_token)
        with open(file_from, 'rb') as f:
            dbx.files_upload(f.read(), file_to, mode=dropbox.files.WriteMode.overwrite)

access_token = "[hidden]"
file_from = "/home/olbliss/"+name
file_to = "/Work/Python Anywhere Backups/"+name
transferData = TransferData(access_token)

try:
    transferData.upload_file(file_from, file_to)
except:
    os.remove(name)
    print('uploaded failed, '+name+' removed from /home/olbliss/')

try:
    os.remove(name)
except:
    pass

Failure message: enter image description here

Upvotes: 1

Views: 604

Answers (1)

Greg
Greg

Reputation: 16930

The 413 status code indicates that the payload was too large. The files_upload method only officially supports files up to 150 MB in size. You'll need to use upload_sessions for larger files.

Here's a basic example that 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 = 8 * 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)
            break
        else:
            dbx.files_upload_session_append_v2(f.read(CHUNK_SIZE),
                                            cursor)
            cursor.offset = f.tell()

f.close()

Note: this should only serve as an example. It hasn't been extensively tested and doesn't implement error handling.

Upvotes: 3

Related Questions