【发布时间】:2021-04-20 00:18:57
【问题描述】:
我有一个返回 FileResponse 的端点。当我使用如下代码时,出现错误“读取已关闭文件” 代码如下所示:
@action(detail=True, methods=['get'], url_path='download')
def get_file(self, request, pk=None):
instance = self.get_object()
fa = getattr(instance, file_location)
if fa:
with open(fa.path, 'rb') as f:
response = FileResponse(f, as_attachment=True)
return response
else:
raise FileNotFound
当我删除 with-block 时,它可以工作。
我需要 with 块吗?
我正在使用邮递员来处理请求
【问题讨论】:
-
documentation 中的示例没有关闭文件。错误是,因为 django 在您返回后尝试访问
open。 -
它说文件会自动关闭,所以不要用上下文管理器打开它。
标签: python django django-rest-framework postman