流式处理请求中Zip文件时遇UnexpectedSignatureError问题求助
流式处理Zip导出文件时遇到UnexpectedSignatureError错误
问题描述
我需要从请求中获取Zip格式的导出文件,后续要上传至云存储,不想将整个文件存入内存,希望逐行下载处理。尝试了以下Python代码:
with requests.get(export_url, stream=True) as response: for file_name, file_size, unzipped_chunks in stream_unzip(response.iter_lines()): for chunk in unzipped_chunks: print(chunk)
但出现错误:
UnexpectedSignatureError: b'<htm'
错误原因
这个错误说明你收到的响应不是Zip文件,而是HTML内容(开头的<htm就是明证)。通常是请求失败导致服务器返回了错误页面(比如404、500,或者需要登录的跳转页面)。
解决方法
1. 先验证请求的有效性
在处理Zip流之前,先确认请求是否成功,打印响应状态码和部分内容排查问题:
with requests.get(export_url, stream=True) as response: print("响应状态码:", response.status_code) print("响应头部Content-Type:", response.headers.get('Content-Type')) print("响应内容前500字节:", response.content[:500])
如果状态码不是200,或者Content-Type不是application/zip,需要先解决请求问题:
- 检查
export_url是否正确 - 确认请求是否需要携带认证信息(比如Cookie、Authorization Token)
- 验证请求头是否符合服务器要求(比如User-Agent、Accept等)
2. 修正流式读取的方式
response.iter_lines()是用于处理文本内容的,会破坏Zip文件的二进制结构,应该用response.iter_content()来获取二进制块:
with requests.get(export_url, stream=True) as response: # 自动抛出HTTP错误(比如404、500) response.raise_for_status() # 确认响应是Zip文件 assert response.headers.get('Content-Type') == 'application/zip', "响应不是Zip文件" # 用iter_content获取二进制流 for file_name, file_size, unzipped_chunks in stream_unzip(response.iter_content(chunk_size=8192)): for chunk in unzipped_chunks: # 这里替换为云存储的流式上传逻辑 # 比如OSS的put_object_from_fileobj,或者S3的upload_fileobj print(chunk)
3. 适配云存储流式上传
主流云存储服务(阿里云OSS、腾讯云COS、AWS S3等)的SDK都支持流式上传,直接将chunk或者unzipped_chunks传入对应的上传接口即可,无需将整个文件加载到内存。
内容的提问来源于stack exchange,提问作者Juanjo
相关产品推荐
相关产品推荐

