Commits

smil...@18c32c52-eb3f-0410-93bd-f15eff1430f4  committed dd12bf1

New main.py with DjangoThumbnail class

  • Participants
  • Parent commits f419ed2
  • Branches smiley-refactor

Comments (0)

Files changed (1)

File thumbnail/main.py

+import os
+
+from django.conf import settings
+from django.utils.encoding import iri_to_uri
+
+from main import Thumbnail, OPTIONS
+
+class DjangoThumbnail(Thumbnail):
+    # filename_format is passed the following string options:
+    #   `filename`  -- original source filename
+    #   `basename`  -- source filename, minus its extensions if it was '.jpg'
+    #   `directory` -- source directory (relative to self.root)
+    #   `quality`   -- the quality of the image
+    #   `options`   -- a list of any non-default settings, each starting with an
+    #                  underscore
+    filename_format = '%s(directory)s/%(basename)s%(options)s_q%(quality)s.jpg'
+    root = settings.MEDIA_ROOT
+    base_url = settings.MEDIA_URL
+
+    def __init__(self, relative_source_path, *args, **kwargs):
+        self.relative_source_path = relative_source_path
+        source_path = self._absolute_path(source_path)
+        thumbnail_path = self._absolute_path(self.relative_thumbnail_path)
+        super(DjangoThumbnail, self).__init__(source_path, thumbnail_path,
+                                              *args, **kwargs)
+
+    def _absolute_path(self, path):
+        return os.path.join(self.root, source_path).encode('utf-8')
+
+    def _get_relative_thumbnail_path(self, source_path):
+        if hasattr(self, '_relative_thumbnail_path'):
+            return self._relative_thumbnail_path
+        source_dir, source_filename = os.path.split(source_path)
+        base, ext = os.path.splitext(source_filename)
+        if ext.lower() == '.jpg':
+            basename = base
+        else:
+            basename = source_filename
+        thumbs_dir = os.path.join(self.root, filehead, self.subdir)
+        if not os.path.isdir(thumbs_dir):
+            os.mkdir(thumbs_dir)
+
+        options = ['_%s' % option for option in OPTIONS if getattr(self, m)]
+        filename_opts = dict(
+            filename=source_filename,
+            basename=basename,
+            directory=source_dir,
+            x=self.size[0],
+            y=self.size[1],
+            quality=self.quality,
+            options=''.join(options)
+        )
+
+        self._relative_thumbnail_path = self.filename_format % filename_opts
+        return self._relative_thumbnail_path
+    relative_thumbnail_path = property(_get_relative_thumbnail_path)
+
+    def _get_url(self):
+        bits = self.relative_thumbnail_path.split(os.path.sep)
+        return iri_to_uri('%s%s' % (self.base_url, '/'.join(bits)))
+    url = property(_get_url)