Dropbox API v2 使用 python 上传大文件

dropbox API v2 upload large files using python

我正在尝试通过 Dropbox API v2 上传大文件 (~900MB),但出现此错误:

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

它适用于较小的文件。

我在文档中发现我需要使用 files_upload_session_start 方法打开上传会话,但我在执行此命令时遇到错误,无法使用 ._append 方法继续。

我该如何解决这个问题?文档中没有信息。 我正在使用 Python 3.5.1 和使用 pip 安装的最新 dropbox 模块。

这是我的代码 运行:

c = Dropbox(access_token)
f = open("D:\Programs\ubuntu-13.10-desktop-amd64.iso", "rb")
result = c.files_upload_session_start(f)
f.seek(0, os.SEEK_END)
size = f.tell()
c.files_upload_session_finish(f,     files.UploadSessionCursor(result.session_id, size), files.CommitInfo("/test900.iso"))

对于这样的大文件,您需要使用上传会话。否则,您将 运行 遇到诸如您发布的错误之类的问题。

这使用 Dropbox Python SDK 将文件从 file_path 指定的本地文件上传到 Dropbox API 到 dest_path 指定的远程路径。它还根据文件的大小选择是否使用上传会话:

import os

from tqdm import tqdm

import dropbox


def upload(
    access_token,
    file_path,
    target_path,
    timeout=900,
    chunk_size=4 * 1024 * 1024,
):
    dbx = dropbox.Dropbox(access_token, timeout=timeout)
    with open(file_path, "rb") as f:
        file_size = os.path.getsize(file_path)
        if file_size <= chunk_size:
            print(dbx.files_upload(f.read(), target_path))
        else:
            with tqdm(total=file_size, desc="Uploaded") as pbar:
                upload_session_start_result = dbx.files_upload_session_start(
                    f.read(chunk_size)
                )
                pbar.update(chunk_size)
                cursor = dropbox.files.UploadSessionCursor(
                    session_id=upload_session_start_result.session_id,
                    offset=f.tell(),
                )
                commit = dropbox.files.CommitInfo(path=target_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()
                    pbar.update(chunk_size)

@Greg 答案可以通过 Dropbox Api v2 调用更新:

self.client.files_upload_session_append_v2(
                f.read(self.CHUNK_SIZE), cursor)
cursor.offset = f.tell()