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

测试signal.py文件出现ValueError: seek of closed file错误,寻求技术帮助

问题排查与解决:ValueError: seek of closed file

问题原因

从代码来看,signals.py里的save_image_to_local函数直接通过default_storage.open()获取文件对象,但没使用上下文管理器(with语句)管理文件生命周期。Python的垃圾回收机制会在文件对象无引用时提前关闭它,而Image对象后续的操作(比如保存)还在尝试读取已关闭的文件,最终触发seek of closed file错误。

另外测试代码里虽用BytesIO模拟了文件内容,但如果信号处理函数里的文件对象被提前关闭,同样会引发该错误。

解决步骤

1. 修正signals.py的文件操作逻辑

把直接打开文件的代码改成with语句,确保文件在图像处理全程保持打开,处理完成后自动安全关闭:

# 原代码
f = default_storage.open(image_path, 'rb')
img = Image.open(f)
# ... 图像处理逻辑
img.save(local_image_path)

# 修改后代码
with default_storage.open(image_path, 'rb') as f:
    img = Image.open(f)
    # ... 保留原图像处理逻辑不变
    img.save(local_image_path)

2. 校验测试逻辑(可选)

如果测试仍有问题,检查test_signals.py中mock_storage.open的返回值是否持续可用:

  • 给BytesIO对象保留引用,避免被提前回收:
def test_save_image_to_local(mock_storage):
    mock_file = BytesIO(b'mock image content')
    mock_storage.open.return_value = mock_file
    # ... 原测试逻辑

验证

修改后重新运行测试,确认ValueError: seek of closed file错误不再出现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:05:24