【问题标题】:Django rest framework do I need to close file before the responseDjango rest框架我需要在响应之前关闭文件吗
【发布时间】: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


【解决方案1】:

正如 cmets 所建议的,不要将此部分包装在上下文管理器中:

response = FileResponse(f, as_attachment=True)
return response

将代码放入上下文管理器会导致重复尝试关闭已关闭的文件。

【讨论】:

    猜你喜欢
    • 2020-08-23
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2020-06-17
    • 2012-08-12
    • 2021-05-02
    • 2023-01-21
    • 2020-03-01
    相关资源
    最近更新 更多