上传大文件时如何显示进度条?
解读
国内一线互联网公司的面试官问这道题,并不是想听你背“tqdm 写个循环”,而是考察三点:
- 是否理解 Requests 上传本质上是「可迭代对象」逐块读文件;
- 能否在不修改 Requests 源码的前提下,用「自定义迭代器 + Hook」优雅注入进度逻辑;
- 是否知道 生产环境要兼顾内存、速率、失败重试与可观测性。
如果直接答“用 tqdm.wrapattr”只能得 60 分;能把 iterable wrapper、requests_toolbelt、MultipartEncoder、回调钩子、日志追踪 串成闭环,才能拿到 90+。
知识点
- Requests 上传流机制:data= 接受 file-like object 或任意可迭代字节块;内部通过
super_len()判断长度,不支持 seek 的流会强制走分块传输(Transfer-Encoding: chunked)。 - toolbelt.MultipartEncoder:官方推荐的大文件表单封装器,自带 read() 回调点,可精确拿到已读字节数。
- tqdm 的“wrap”与“update”两种模式:wrap 适合 fileobj,update 适合自定义迭代器;多线程场景必须用 tqdm.contrib.concurrent 的锁。
- Hook 注入点:Requests 的
hooks={'data': func}只能拿到最终字节串,无法做流式统计;因此进度逻辑必须写在「数据生产端」而非「数据消费端」。 - 可观测性:国内审计要求 日志里必须带 traceId,进度回调里要能把
X-B3-TraceId打进去,方便链路排查。 - 性能陷阱:默认 chunk 大小 1024 字节太小,内网千兆环境建议 256 KB;HTTPS 加密线程饥饿 时要用
urllib3.util.make_headers(keep_alive=True)复用连接。
答案
import os, requests
from requests_toolbelt import MultipartEncoder
from tqdm import tqdm
def upload_with_progress(upload_url: str, file_path: str, fields: dict=None, headers: dict=None):
file_size = os.path.getsize(file_path)
# 1. 构造表单,file 字段用 (filename, fileobj, mimetype) 三元组
_fields = fields or {}
_fields['file'] = (os.path.basename(file_path), open(file_path, 'rb'), 'application/octet-stream')
encoder = MultipartEncoder(fields=_fields)
# 2. 创建 tqdm 进度条,unit_scale 让单位自动变成 MB
bar = tqdm(total=file_size, unit='B', unit_scale=True, desc='Upload')
# 3. 自定义 read 包装器,每次 read 后更新进度
def callback(monitor):
bar.update(monitor.bytes_read - callback.last_read)
callback.last_read = monitor.bytes_read
callback.last_read = 0
# 4. 用 monitor 包装 encoder,把 callback 挂上去
from requests_toolbelt import MultipartEncoderMonitor
monitor = MultipartEncoderMonitor(encoder, callback)
# 5. 发请求,headers 里带上正确的 Content-Type
_headers = headers or {}
_headers['Content-Type'] = monitor.content_type
try:
resp = requests.post(upload_url, data=monitor, headers=_headers)
resp.raise_for_status()
return resp
finally:
bar.close()
关键点强调:
- 进度逻辑写在 MultipartEncoderMonitor 的回调里,对 Requests 零侵入;
- with 语义:生产代码要把 open(file_path, 'rb') 放进 with,防止异常时句柄泄漏;
- 重试策略:接入
urllib3.Retry(total=3, backoff_factor=1),进度条在重试时会重新归零,需要额外封装“断点续传”逻辑才能连续累加。
拓展思考
- 非 multipart 裸流上传:如果后端只接受 raw binary,自定义迭代器每次 yield 256 KB,并在
__next__里手动 update(tqdm);此时 Requests 不会自动加 Content-Length,需要提前os.fstat(fp.fileno()).st_size手动设置,**否则 Nginx 反向代理会返回 411。 - 多文件并发上传:使用
concurrent.futures.ThreadPoolExecutor,每个线程独享一个 tqdm 实例,通过tqdm.set_lock(RLock())防止终端错位;阿里 OSS 单连接限速 5 Gbps,线程数超过 8 反而下降。 - 浏览器端对齐:国内很多场景需要 前后端进度一致,后端通过
X-Progress-Id把进度写 Redis,WebSocket 推送;Requests 侧在回调里同步X-Progress-Id与已读字节,保证两端刻度误差 <1%。 - 可测试性:单元测试时用
io.BytesIO(b'0'*100_000_000)构造假大文件,配合 responses 库 mock 掉真实网络,让 CI 在 2 秒内跑完;切记关闭 tqdm 输出,否则 GitLab CI 日志会爆炸。