You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

offset是否有默认值?如何为上传进度回调函数添加文件参数?

问题解决思路与代码修改

先搞懂offset参数的赋值逻辑

create_upload_session是SharePoint Python SDK的分块上传方法,它会自动把当前已上传的总字节数作为offset参数传给你指定的进度回调函数。比如你设置的size_chunk是1MB,每传完一块,就会调用一次进度函数,并把累计上传的字节数(1000000、2000000...直到文件总大小)作为offset传进去。

修改方案:给进度函数添加当前文件参数

因为create_upload_session只会给回调函数传offset一个参数,要把当前上传的文件路径传进去,得用闭包/匿名函数包装一下,把文件路径“绑定”到回调函数里。具体步骤如下:

1. 修改进度回调函数

把原来依赖全局local_path的逻辑改成接收文件路径参数,让每个文件上传时都能获取自己的大小:

def print_upload_progress(file_path, offset):
    # type: (str, int) -> None
    file_size = os.path.getsize(file_path)
    print(
        "Uploaded '{0}' bytes from '{1}'...[{2}%]".format(
            offset, file_size, round(offset / file_size * 100, 2)
        )
    )

2. 在上传循环中包装回调函数

在upload_file_2_sp的循环里,用lambda把当前的file传给print_upload_progress,同时保留offset参数供SDK传递:

def upload_file_2_sp(report_list, base_url, target_url):
    ctx = sharepointConnection(base_url)

    target_folder = ctx.web.get_folder_by_server_relative_url(target_url)
    size_chunk = 1000000

    for file in report_list:
        # 用lambda包装回调,把当前file作为第一个参数传入
        progress_callback = lambda offset: print_upload_progress(file, offset)
        uploaded_file = target_folder.files.create_upload_session(
            file, size_chunk, progress_callback
        ).execute_query()

        print("File {0} has been uploaded successfully".format(uploaded_file.serverRelativeUrl))

为什么这么改?

  • lambda函数在这里充当适配器:它只接收SDK传来的offset,然后把当前循环的file和offset一起传给修改后的进度函数。
  • 这样每个文件上传时,进度函数都能拿到对应文件的路径,计算并显示该文件的上传进度,不再和全局的local_path绑定。

内容的提问来源于stack exchange,提问作者intransigent_rocker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 19:22:13