Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Did this module ever close a file? #155

Open
filwaline opened this issue Feb 20, 2020 · 4 comments
Open

Did this module ever close a file? #155

filwaline opened this issue Feb 20, 2020 · 4 comments

Comments

@filwaline
Copy link

DownloadMixin need a File object to serve, and open file in get_file method, but I never found a close call(by global text search).
Did you close file somewhere? Or Using context manager with?

https://docs.djangoproject.com/en/2.2/topics/files/#the-file-object

If open too many file and never close them, IOError will raise.

IOError: [Errno 24] Too many open files
@Natim
Copy link
Collaborator

Natim commented Oct 5, 2020

@filwaline that's an interesting question. Do you have a way to fix this in mind?

@filwaline
Copy link
Author

filwaline commented Oct 11, 2020

use @contextlib.contextmanager

@contextlib.contextmanager
def get_file(self):
    fileobject = open(...)
    try:
        yield fileobject
    finally:
        fileobject.close()
    try:
        with self.get_file() as f:
            self.file_instance = f
            
            # Respect the If-Modified-Since header.
            since = self.request.META.get("HTTP_IF_MODIFIED_SINCE", None)
            if since is not None:
                if not self.was_modified_since(self.file_instance, since):
                    return self.not_modified_response(**response_kwargs)
            # Return download response.
            return self.download_response(*response_args, **response_kwargs)

    except exceptions.FileNotFound:
        return self.file_not_found_response()

https://github.com/jazzband/django-downloadview/blob/master/django_downloadview/views/base.py#L144

code not tested, but it should work

@Natim
Copy link
Collaborator

Natim commented Oct 12, 2020

Do you mind creating a pull-request with your fix?

@filwaline
Copy link
Author

Maybe later

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants