Commits

Alex Ulianytskyi committed f320b29

Initial commit

  • Participants

Comments (0)

Files changed (5)

+\.orig$
+\.orig\..*$
+\.chg\..*$
+\.rej$
+\.conflict\~$
+^nbproject
+^tmp
+\.py[c|o]$
+\.tmp$
+\.log$

__init__.py

Empty file added.
+# -*- coding: utf-8 -*-
+import os
+from hashlib import md5
+from django.db.models.query import QuerySet
+from django.db.models import Model
+
+def upload_image(property, template=None, hash_from=None, hash_func=md5):
+    def wrapped(instance, filename):
+        new_filename = filename
+        if instance.pk is None:
+            instance.save()
+        new_filename = instance.pk
+        name, extension = os.path.splitext(filename)
+        extension = extension.lower()
+        if hash_from is not None:
+            hash_from_str = str(getattr(instance, hash_from, 'id'))
+            hash = hash_func(hash_from_str.lower()).hexdigest()
+            new_filename = u'%s%s' % (hash, extension)
+        if template is not None:
+            opts = {}
+            opts.update(instance.__dict__)
+            opts.update(
+                        {'FILENAME': filename,
+                        'NAME': name,
+                        'EXTENSION': extension})
+            new_filename = template % opts
+            new_filename.strip('/ ')
+        image = getattr(instance, property)
+        if image.storage.exists(new_filename):
+            image.storage.delete(new_filename)
+        return new_filename
+    return wrapped
+
+def generic(generic_func, ** default_kw):
+    def decorator(func):
+        def wrapper(request, ** kwargs):
+            generic_kw = func(request, ** kwargs)
+            generic_kw.update(default_kw)
+            model = generic_kw.get('model', None)
+            if model is not None:
+                queryset = model.objects.all()
+                generic_kw['queryset'] = queryset
+            else:
+                queryset = generic_kw.get('queryset')
+                model = queryset.model
+            generic_kw['template_object_name'] = model.__name__.lower()
+            generic_kw['template_name'] = u'%s.html' % generic_func.func_name.replace('object', model.__name__.lower())
+            generic_kw['paginate_by'] = 25
+            del generic_kw['model']
+            try:
+                return generic_func(request, ** generic_kw)
+            except TypeError:
+                del generic_kw['paginate_by']
+                return generic_func(request, ** generic_kw)
+        return wrapper
+    return decorator
+# -*- coding: utf-8 -*-
+import os
+from PIL import Image
+from django.conf import settings
+from django.core.files.storage import FileSystemStorage
+
+class ImageStorage(FileSystemStorage):
+    thumbnail_size = (100, 100)
+    thumbnail_suffix = '.thumb'
+    image_size = (1000, 1000)
+
+    def _thumbnail(self, name, size, suffix=None):
+        path = self.path(name)
+        thumbnail_name = path
+        img = Image.open(path)
+        if img.size[0] < size[0] and img.size[1] < size[1]:
+            return
+        _name, ext = os.path.splitext(path)
+        if suffix:
+            thumbnail_name = u'%s%s%s' % (_name, suffix, ext)
+        img.thumbnail(size, Image.ANTIALIAS)
+        img.save(thumbnail_name)
+        return thumbnail_name
+
+    def __init__(self, location, base_url, ** options):
+        """
+        options can be:
+            bool do_tumbnail - create thumbnail image using `THUMBNAIL_SIZE` sttings value
+            bool do_resize - resize big image to not grether then size defined in `IMAGE_SIZE` settings value
+            int thumbnail_size - overwrite `THUMBNAIL_SIZE`
+            int thumbnail_suffix - overwrite `THUMBNAIL_SUFFIX`
+            int image_size - overwrite `IMAGE_SIZE`
+        """
+        if hasattr(settings, 'THUMBNAIL_SIZE'):
+            self.thumbnail_size = settings.THUMBNAIL_SIZE
+        if hasattr(settings, 'THUMBNAIL_SUFFIX'):
+            self.thumbnail_suffix = settings.THUMBNAIL_SUFFIX
+        if hasattr(settings, 'IMAGE_SIZE'):
+            self.size = settings.IMAGE_SIZE
+
+        self.do_thumbnail = options.get('do_thumbnail', True)
+        self.do_resize = options.get('do_resize', True)
+        if options.has_key('thumbnail_size'):
+            self.thumbnail_size = options.get('thumbnail_size')
+        if options.has_key('thumbnail_suffix'):
+            self.thumbnail_suffix = options.get('thumbnail_suffix')
+        if options.has_key('image_size'):
+            self.image_size = options.get('image_size')
+        super(ImageStorage, self).__init__(location, base_url)
+
+    def _save(self, name, content):
+        super(ImageStorage, self)._save(name, content)
+        if self.do_thumbnail:
+            self._thumbnail(name, self.thumbnail_size, self.thumbnail_suffix)
+        if self.do_resize:
+            self._thumbnail(name, self.image_size)
+        return name
+    # TODO: Автоматичекое добавление метода get_thumbnail_url к модели
+    def get_thumbnail_url(self, name):
+        _name, ext = os.path.splitext(self.url(name))
+        if _name is not u'':
+            return u'%s%s%s' % (_name, self.thumbnail_suffix, ext)
+        else:
+            return u''

static_urlconf.py

+# -*- coding: utf-8 -*-
+from django.conf.urls.defaults import *
+from django.conf import settings
+
+urlpatterns = patterns('',
+        url(r'^favicon.ico$', 'django.views.static.serve',
+            {'path': '/img/favicon.ico', 'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
+        url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.strip('/'), 'django.views.static.serve',
+            {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
+)