Skip to content

Can't use open as context manager with ThumbnailFile #669

@Chadys

Description

@Chadys

Problem

ThumbnailFile.open is currently implemented as:

    def open(self, mode=None, *args, **kwargs):
        if self.closed and self.name:
            mode = mode or getattr(self, 'mode', None) or 'rb'
            self.file = self.storage.open(self.name, mode)
        else:
            return super().open(mode, *args, **kwargs)

When the first predicate is True, the function never returns anything.
Which means we get an error if we try to use .open() as a context manager: with thumbnail_file.open() will crash, which is not the case when using django's FieldFile.open.

Potential solution

I didn't dig too deep into easy-thumbnail code base but from my shallow understanding, to get the same behaviour as FieldFile, the fix is as simple as adding:

    def open(self, mode=None, *args, **kwargs):
        if self.closed and self.name:
            mode = mode or getattr(self, 'mode', None) or 'rb'
            self.file = self.storage.open(self.name, mode)
            return self  # <-- added line here
        else:
            return super().open(mode, *args, **kwargs)

Workarounds

In the meantime, you can:

  • not use context manager, call open and close explicitely
  • monkeypatch:
from easy_thumbnails.files import ThumbnailFile 

def _patched_thumbnail_open(self, mode=None, *args, **kwargs):
    return ThumbnailFile.open(self, mode, *args, **kwargs) or self

thumbnail_file.open = _patched_thumbnail_open.__get__(file)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions