1

I have an endpoint returning a FileResponse. When I use a code like the following I get an error 'read of closed file' The code looks like this:

    @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

when I remove the with-block it works.

Do I need the with block?

I'm using postman for the request

lando
  • 335
  • 1
  • 16
  • The example in the [documentation](https://docs.djangoproject.com/en/3.1/ref/request-response/#fileresponse-objects) is not closing the file. The error is, because django tries to access the `open` after you've returned. – Countour-Integral Jan 14 '21 at 23:14
  • it says **The file will be closed automatically, so don’t open it with a context manager.** – Countour-Integral Jan 14 '21 at 23:16

1 Answers1

2

As the comments suggest, just don't wrap this part in a context manager:

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

Putting the code in a context manager causes a duplicate try to close the file when it is already closed.

therealak12
  • 1,178
  • 2
  • 12
  • 26