Skip to content

Commit de5a15d

Browse files
committed
Make thumbnail tag be compatible with custom storage engine
* Doesn't create thumbnails in local fs while using custom storage * Fix existence check logic with custom storage
1 parent cf6c79c commit de5a15d

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

mezzanine/core/templatetags/mezzanine_tags.py

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from future.builtins import int, open, str
33

44
from hashlib import md5
5+
import io
56
import os
67
try:
78
from urllib.parse import quote, unquote
@@ -312,11 +313,14 @@ def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5,
312313
# image, which is something we do in filebrowser when a new image
313314
# is written, allowing us to purge any previously generated
314315
# thumbnails that may match a new image name.
315-
thumb_dir = os.path.join(settings.MEDIA_ROOT, image_dir,
316-
settings.THUMBNAILS_DIR_NAME, image_name)
317-
if not os.path.exists(thumb_dir):
316+
thumb_dir = os.path.join(
317+
image_dir,
318+
settings.THUMBNAILS_DIR_NAME,
319+
image_name
320+
)
321+
if not default_storage.exists(thumb_dir):
318322
try:
319-
os.makedirs(thumb_dir)
323+
default_storage.makedirs(thumb_dir)
320324
except OSError:
321325
pass
322326

@@ -329,7 +333,7 @@ def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5,
329333
thumb_url = "%s/%s" % (image_url_path, thumb_url)
330334

331335
try:
332-
thumb_exists = os.path.exists(thumb_path)
336+
thumb_exists = default_storage.exists(thumb_path)
333337
except UnicodeEncodeError:
334338
# The image that was saved to a filesystem with utf-8 support,
335339
# but somehow the locale has changed and the filesystem does not
@@ -421,21 +425,12 @@ def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5,
421425
to_size = (to_width, to_height)
422426
to_pos = (left, top)
423427
try:
428+
print('GEN [%s].' % thumb_url)
429+
output = io.BytesIO()
424430
image = ImageOps.fit(image, to_size, Image.ANTIALIAS, 0, to_pos)
425-
image = image.save(thumb_path, filetype, quality=quality, **image_info)
426-
# Push a remote copy of the thumbnail if MEDIA_URL is
427-
# absolute.
428-
if "://" in settings.MEDIA_URL:
429-
with open(thumb_path, "rb") as f:
430-
default_storage.save(unquote(thumb_url), File(f))
431+
image = image.save(output, filetype, quality=quality, **image_info)
432+
default_storage.save(unquote(thumb_url), File(output))
431433
except Exception:
432-
# If an error occurred, a corrupted image may have been saved,
433-
# so remove it, otherwise the check for it existing will just
434-
# return the corrupted image next time it's requested.
435-
try:
436-
os.remove(thumb_path)
437-
except Exception:
438-
pass
439434
return image_url
440435
return thumb_url
441436

0 commit comments

Comments
 (0)