我正在尝试通过 Dropbox API v2 上传大文件 (~900MB),但出现此错误:
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))
它适用于较小的文件。
我在文档中发现我需要使用 files_upload_session_start
方法打开上传 session ,但我在执行此命令时遇到错误,我无法继续使用 ._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"))
最佳答案
对于这样的大文件,您需要使用上传 session 。否则,您会遇到诸如您发布的错误之类的问题。
这使用了 Dropbox Python SDK将文件从 file_path
指定的本地文件上传到 Dropbox API 到 dest_path
指定的远程路径。它还根据文件的大小选择是否使用上传 session :
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)
关于python - Dropbox API v2 使用 python 上传大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397966/