Esempio n. 1
0
def thumbnails_for_file(relative_source_path, root=None, basedir=None,
                        subdir=None, prefix=None):
    """
    Return a list of dictionaries, one for each thumbnail belonging to the
    source image.

    The following list explains each key of the dictionary:

      `filename`  -- absolute thumbnail path
      `x` and `y` -- the size of the thumbnail
      `options`   -- list of options for this thumbnail
      `quality`   -- quality setting for this thumbnail
    """
    # Fall back to using thumbnail settings. These are local imports so that
    # there is no requirement of Django to use the utils module.
    if root is None:
        from django.conf import settings
        root = settings.MEDIA_ROOT
    if prefix is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        prefix = get_thumbnail_setting('PREFIX')
    if subdir is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        subdir = get_thumbnail_setting('SUBDIR')
    if basedir is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        basedir = get_thumbnail_setting('BASEDIR')
    source_dir, filename = os.path.split(relative_source_path)
    thumbs_path = os.path.join(root, basedir, source_dir, subdir)
    if not os.path.isdir(thumbs_path):
        return []
    files = all_thumbnails(thumbs_path, recursive=False, prefix=prefix,
                           subdir='')
    return files.get(filename, [])
Esempio n. 2
0
def thumbnails_for_file(relative_source_path, root=None, basedir=None,
                        subdir=None, prefix=None):
    """
    Return a list of dictionaries, one for each thumbnail belonging to the
    source image.

    The following list explains each key of the dictionary:

      `filename`  -- absolute thumbnail path
      `x` and `y` -- the size of the thumbnail
      `options`   -- list of options for this thumbnail
      `quality`   -- quality setting for this thumbnail
    """
    # Fall back to using thumbnail settings. These are local imports so that
    # there is no requirement of Django to use the utils module.
    if root is None:
        from django.conf import settings
        root = settings.MEDIA_ROOT
    if prefix is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        prefix = get_thumbnail_setting('PREFIX')
    if subdir is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        subdir = get_thumbnail_setting('SUBDIR')
    if basedir is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        basedir = get_thumbnail_setting('BASEDIR')
    source_dir, filename = os.path.split(relative_source_path)
    thumbs_path = os.path.join(root, basedir, source_dir, subdir)
    if not os.path.isdir(thumbs_path):
        return []
    files = all_thumbnails(thumbs_path, recursive=False, prefix=prefix,
                           subdir='')
    return files.get(filename, [])
    def __init__(self,
                 relative_source,
                 requested_size,
                 opts=None,
                 quality=None,
                 basedir=None,
                 subdir=None,
                 prefix=None,
                 relative_dest=None,
                 processors=None,
                 extension=None):

        if isinstance(relative_source, basestring):
            relative_source = force_unicode(relative_source)
            # Set the absolute filename for the source file
            source = self._absolute_path(relative_source)
        else:
            source = relative_source

        quality = get_thumbnail_setting('QUALITY', quality)
        convert_path = get_thumbnail_setting('CONVERT')
        wvps_path = get_thumbnail_setting('WVPS')
        if processors is None:
            processors = PROCESSORS  #dynamic_import(get_thumbnail_setting('PROCESSORS'))

        # Call super().__init__ now to set the opts attribute. generate() won't
        # get called because we are not setting the dest attribute yet.
        super(_DjangoThumbnail, self).__init__(source,
                                               requested_size,
                                               opts=opts,
                                               quality=quality,
                                               convert_path=convert_path,
                                               wvps_path=wvps_path,
                                               processors=processors)

        # Get the relative filename for the thumbnail image, then set the
        # destination filename
        if relative_dest is None:
            relative_dest = \
               self._get_relative_thumbnail(relative_source, basedir=basedir,
                                            subdir=subdir, prefix=prefix,
                                            extension=extension)
        filelike = not isinstance(relative_dest, basestring)
        if filelike:
            self.dest = relative_dest
        else:
            self.dest = self._absolute_path(relative_dest)

        # Call generate now that the dest attribute has been set
        self.generate()

        # Set the relative & absolute url to the thumbnail
        if not filelike:
            self.relative_url = filepath_to_uri(relative_dest)
            self.absolute_url = '%s%s' % (settings.MEDIA_URL,
                                          self.relative_url)
Esempio n. 4
0
def all_thumbnails(path, recursive=True, prefix=None, subdir=None):
    """
    Return a dictionary referencing all files which match the thumbnail format.

    Each key is a source image filename, relative to path.
    Each value is a list of dictionaries as explained in `thumbnails_for_file`.
    """
    # Fall back to using thumbnail settings. These are local imports so that
    # there is no requirement of Django to use the utils module.
    if prefix is None:
        from sorl.thumbnail.main import get_thumbnail_setting

        prefix = get_thumbnail_setting("PREFIX")
    if subdir is None:
        from sorl.thumbnail.main import get_thumbnail_setting

        subdir = get_thumbnail_setting("SUBDIR")
    thumbnail_files = {}
    if not path.endswith("/"):
        path = "%s/" % path
    len_path = len(path)
    if recursive:
        all = os.walk(path)
    else:
        files = []
        for file in os.listdir(path):
            if os.path.isfile(os.path.join(path, file)):
                files.append(file)
        all = [(path, [], files)]
    for dir_, subdirs, files in all:
        rel_dir = dir_[len_path:]
        for file in files:
            thumb = re_thumbnail_file.match(file)
            if not thumb:
                continue
            d = thumb.groupdict()
            source_filename = d.pop("source_filename")
            if prefix:
                source_path, source_filename = os.path.split(source_filename)
                if not source_filename.startswith(prefix):
                    continue
                source_filename = os.path.join(source_path, source_filename[len(prefix) :])
            d["options"] = d["options"] and d["options"].split("_") or []
            if subdir and rel_dir.endswith(subdir):
                rel_dir = rel_dir[: -len(subdir)]
            # Corner-case bug: if the filename didn't have an extension but did
            # have an underscore, the last underscore will get converted to a
            # '.'.
            m = re.match(r"(.*)_(.*)", source_filename)
            if m:
                source_filename = "%s.%s" % m.groups()
            filename = os.path.join(rel_dir, source_filename)
            thumbnail_file = thumbnail_files.setdefault(filename, [])
            d["filename"] = os.path.join(dir_, file)
            thumbnail_file.append(d)
    return thumbnail_files
Esempio n. 5
0
def all_thumbnails(path, recursive=True, prefix=None, subdir=None):
    """
    Return a dictionary referencing all files which match the thumbnail format.

    Each key is a source image filename, relative to path.
    Each value is a list of dictionaries as explained in `thumbnails_for_file`.
    """
    # Fall back to using thumbnail settings. These are local imports so that
    # there is no requirement of Django to use the utils module.
    if prefix is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        prefix = get_thumbnail_setting('PREFIX')
    if subdir is None:
        from sorl.thumbnail.main import get_thumbnail_setting
        subdir = get_thumbnail_setting('SUBDIR')
    thumbnail_files = {}
    if not path.endswith('/'):
        path = '%s/' % path
    len_path = len(path)
    if recursive:
        all = os.walk(path)
    else:
        files = []
        for file in os.listdir(path):
            if os.path.isfile(os.path.join(path, file)):
                files.append(file)
        all = [(path, [], files)]
    for dir_, subdirs, files in all:
        rel_dir = dir_[len_path:]
        for file in files:
            thumb = re_thumbnail_file.match(file)
            if not thumb:
                continue
            d = thumb.groupdict()
            source_filename = d.pop('source_filename')
            if prefix:
                source_path, source_filename = os.path.split(source_filename)
                if not source_filename.startswith(prefix):
                    continue
                source_filename = os.path.join(source_path,
                    source_filename[len(prefix):])
            d['options'] = d['options'] and d['options'].split('_') or []
            if subdir and rel_dir.endswith(subdir):
                rel_dir = rel_dir[:-len(subdir)]
            # Corner-case bug: if the filename didn't have an extension but did
            # have an underscore, the last underscore will get converted to a
            # '.'.
            m = re.match(r'(.*)_(.*)', source_filename)
            if m:
                source_filename = '%s.%s' % m.groups()
            filename = os.path.join(rel_dir, source_filename)
            thumbnail_file = thumbnail_files.setdefault(filename, [])
            d['filename'] = os.path.join(dir_, file)
            thumbnail_file.append(d)
    return thumbnail_files
Esempio n. 6
0
 def _image_repr(self):
     return '<img src="%s_%sx%s_crop_q%s.jpg" />' % (
         os.path.join(settings.MEDIA_URL, self.__dict__[self.image_field].replace(".", "_")),
         self.thumb_width,
         self.thumb_height,
         get_thumbnail_setting("QUALITY"),
     )
Esempio n. 7
0
 def render(self, context):
     # Note that this isn't a global constant because we need to change the
     # value for tests.
     DEBUG = get_thumbnail_setting('DEBUG')
     try:
         # A file object will be allowed in DjangoThumbnail class
         relative_source = self.source_var.resolve(context)
     except VariableDoesNotExist:
         if DEBUG:
             raise VariableDoesNotExist("Variable '%s' does not exist." %
                     self.source_var)
         else:
             relative_source = None
     try:
         requested_size = self.size_var.resolve(context)
     except VariableDoesNotExist:
         if DEBUG:
             raise TemplateSyntaxError("Size argument '%s' is not a"
                     " valid size nor a valid variable." % self.size_var)
         else:
             requested_size = None
     # Size variable can be either a tuple/list of two integers or a valid
     # string, only the string is checked.
     else:
         if isinstance(requested_size, basestring):
             m = size_pat.match(requested_size)
             if m:
                 requested_size = (int(m.group(1)), int(m.group(2)))
             elif DEBUG:
                 raise TemplateSyntaxError("Variable '%s' was resolved but "
                         "'%s' is not a valid size." %
                         (self.size_var, requested_size))
             else:
                 requested_size = None
     if relative_source is None or requested_size is None:
         thumbnail = ''
     else:
         try:
             kwargs = {}
             for key, value in self.kwargs.items():
                 kwargs[key] = value.resolve(context)
             opts = dict([(k, v and v.resolve(context))
                          for k, v in self.opts.items()])
             thumbnail = DjangoThumbnail(relative_source, requested_size,
                             opts=opts, processors=PROCESSORS, **kwargs)
         except:
             if DEBUG:
                 raise
             else:
                 thumbnail = ''
     # Return the thumbnail class, or put it on the context
     if self.context_name is None:
         return thumbnail
     # We need to get here so we don't have old values in the context
     # variable.
     context[self.context_name] = thumbnail
     return ''
Esempio n. 8
0
    def __init__(self, relative_source, requested_size, opts=None,
                 quality=None, basedir=None, subdir=None, prefix=None,
                 relative_dest=None, processors=None, extension=None):

        if isinstance(relative_source, basestring):
            relative_source = force_unicode(relative_source)
            # Set the absolute filename for the source file
            source = self._absolute_path(relative_source)
        else:
            source = relative_source

        quality = get_thumbnail_setting('QUALITY', quality)
        convert_path = get_thumbnail_setting('CONVERT')
        wvps_path = get_thumbnail_setting('WVPS')
        if processors is None:
            processors = PROCESSORS #dynamic_import(get_thumbnail_setting('PROCESSORS'))

        # Call super().__init__ now to set the opts attribute. generate() won't
        # get called because we are not setting the dest attribute yet.
        super(_DjangoThumbnail, self).__init__(source, requested_size,
            opts=opts, quality=quality, convert_path=convert_path,
            wvps_path=wvps_path, processors=processors)

        # Get the relative filename for the thumbnail image, then set the
        # destination filename
        if relative_dest is None:
            relative_dest = \
               self._get_relative_thumbnail(relative_source, basedir=basedir,
                                            subdir=subdir, prefix=prefix,
                                            extension=extension)
        filelike = not isinstance(relative_dest, basestring)
        if filelike:
            self.dest = relative_dest
        else:
            self.dest = self._absolute_path(relative_dest)

        # Call generate now that the dest attribute has been set
        self.generate()

        # Set the relative & absolute url to the thumbnail
        if not filelike:
            self.relative_url = filepath_to_uri(relative_dest)
            self.absolute_url = '%s%s' % (settings.MEDIA_URL,
                                          self.relative_url)
Esempio n. 9
0
    def testFilenameGeneration(self):
        basename = RELATIVE_PIC_NAME.replace('.', '_')
        # Basic filename
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)

        # Changed quality and cropped
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120),
                                opts=['crop'],
                                quality=95)
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_crop_q95.jpg'
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # All options on
        processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))
        valid_options = get_valid_options(processors)

        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120),
                                opts=valid_options)
        expected = (os.path.join(settings.MEDIA_ROOT, basename) + '_240x120_'
                    'autocrop_bw_crop_detail_max_sharpen_upscale_q85.jpg')
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # Different basedir
        basedir = 'sorl-thumbnail-test-basedir'
        self.change_settings.change({'BASEDIR': basedir})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(basedir, self.sub_dir, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different subdir
        self.change_settings.change({'BASEDIR': '', 'SUBDIR': 'subdir'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT,
                                os.path.basename(self.sub_dir), 'subdir',
                                basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different prefix
        self.change_settings.change({'SUBDIR': '', 'PREFIX': 'prefix-'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(self.sub_dir, 'prefix-' + basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
Esempio n. 10
0
    def testFilenameGeneration(self):
        basename = RELATIVE_PIC_NAME.replace('.', '_')
        # Basic filename
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)

        # Changed quality and cropped
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120), opts=['crop'],
                                quality=95)
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_crop_q95.jpg'
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # All options on
        processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))
        valid_options = get_valid_options(processors)

        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120), opts=valid_options)
        expected = (os.path.join(settings.MEDIA_ROOT, basename) + '_240x120_'
                    'autocrop_bw_crop_detail_max_sharpen_upscale_q85.jpg')
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # Different basedir
        basedir = 'sorl-thumbnail-test-basedir'
        self.change_settings.change({'BASEDIR': basedir})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(basedir, self.sub_dir, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different subdir
        self.change_settings.change({'BASEDIR': '', 'SUBDIR': 'subdir'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT,
                                os.path.basename(self.sub_dir), 'subdir',
                                basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different prefix
        self.change_settings.change({'SUBDIR': '', 'PREFIX': 'prefix-'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(self.sub_dir, 'prefix-' + basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
Esempio n. 11
0
    def render(self, context):
        # Note that this isn't a global constant because we need to change the
        # value for tests.
        DEBUG = get_thumbnail_setting('DEBUG')
        # Resolve source variable
        try:
            relative_source = force_unicode(self.source_var.resolve(context))
        except VariableDoesNotExist:
            if DEBUG:
                raise VariableDoesNotExist("Variable '%s' does not exist." %
                                           self.source_var)
            else:
                relative_source = None
        # Resolve and check size variable
        if self.requested_size is None:
            try:
                size = self.size_var.resolve(context)
            except VariableDoesNotExist:
                if DEBUG:
                    raise TemplateSyntaxError("Size argument '%s' is not a"
                        " valid size nor a valid variable." % self.size_var)
            else:
                if isinstance(size, basestring):
                    m = size_pat.match(size)
                    if m:
                        size = (int(m.group(1)), int(m.group(2)))
                    elif DEBUG:
                        msg = "Variable '%s' was resolved but '%s' is not a "\
                              "valid size." % (self.size_var, size)
                        raise TemplateSyntaxError(msg)
                self.requested_size = size

        # Get thumbnail instance
        try:
            thumbnail = DjangoThumbnail(relative_source, self.requested_size,
                                        opts=self.opts, processors=PROCESSORS,
                                        **self.kwargs)
        except:
            if DEBUG:
                raise
            else:
                thumbnail = ''

        # Return the thumbnail class, or put it on the context
        if self.context_name is None:
            return thumbnail
        # We need to get here so we don't have old values in the context
        # variable.
        context[self.context_name] = thumbnail
        return ''
def get_thumbnail_path(path):
    basedir = get_thumbnail_setting('BASEDIR')
    subdir = get_thumbnail_setting('SUBDIR')
    return os.path.join(basedir, path, subdir)
class _DjangoThumbnail(SorlThumbnail):
    imagemagick_file_types = get_thumbnail_setting('IMAGEMAGICK_FILE_TYPES')

    def __init__(self,
                 relative_source,
                 requested_size,
                 opts=None,
                 quality=None,
                 basedir=None,
                 subdir=None,
                 prefix=None,
                 relative_dest=None,
                 processors=None,
                 extension=None):

        if isinstance(relative_source, basestring):
            relative_source = force_unicode(relative_source)
            # Set the absolute filename for the source file
            source = self._absolute_path(relative_source)
        else:
            source = relative_source

        quality = get_thumbnail_setting('QUALITY', quality)
        convert_path = get_thumbnail_setting('CONVERT')
        wvps_path = get_thumbnail_setting('WVPS')
        if processors is None:
            processors = PROCESSORS  #dynamic_import(get_thumbnail_setting('PROCESSORS'))

        # Call super().__init__ now to set the opts attribute. generate() won't
        # get called because we are not setting the dest attribute yet.
        super(_DjangoThumbnail, self).__init__(source,
                                               requested_size,
                                               opts=opts,
                                               quality=quality,
                                               convert_path=convert_path,
                                               wvps_path=wvps_path,
                                               processors=processors)

        # Get the relative filename for the thumbnail image, then set the
        # destination filename
        if relative_dest is None:
            relative_dest = \
               self._get_relative_thumbnail(relative_source, basedir=basedir,
                                            subdir=subdir, prefix=prefix,
                                            extension=extension)
        filelike = not isinstance(relative_dest, basestring)
        if filelike:
            self.dest = relative_dest
        else:
            self.dest = self._absolute_path(relative_dest)

        # Call generate now that the dest attribute has been set
        self.generate()

        # Set the relative & absolute url to the thumbnail
        if not filelike:
            self.relative_url = filepath_to_uri(relative_dest)
            self.absolute_url = '%s%s' % (settings.MEDIA_URL,
                                          self.relative_url)

    def _get_relative_thumbnail(self,
                                relative_source,
                                basedir=None,
                                subdir=None,
                                prefix=None,
                                extension=None):
        """
        Returns the thumbnail filename including relative path.
        """
        return build_thumbnail_name(relative_source, self.requested_size,
                                    self.opts, self.quality, basedir, subdir,
                                    prefix, extension)

    def _absolute_path(self, filename):
        absolute_filename = os.path.join(settings.MEDIA_ROOT, filename)
        return absolute_filename.encode(settings.FILE_CHARSET)

    def __unicode__(self):
        return self.absolute_url
Esempio n. 14
0
from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.thumbnail.processors import dynamic_import, get_valid_options

register = Library()

size_pat = re.compile(r'(\d+)x(\d+)$')
quality_pat = re.compile(r'quality=([1-9]\d?|100)$')

filesize_formats = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
filesize_long_formats = {
    'k': 'kilo', 'M': 'mega', 'G': 'giga', 'T': 'tera', 'P': 'peta',
    'E': 'exa', 'Z': 'zetta', 'Y': 'yotta'
}

try:
    PROCESSORS = dynamic_import(get_thumbnail_setting('PROCESSORS'))
    VALID_OPTIONS = get_valid_options(PROCESSORS)
except:
    if get_thumbnail_setting('DEBUG'):
        raise
    else:
        PROCESSORS = []
        VALID_OPTIONS = []


class ThumbnailNode(Node):
    def __init__(self, source_var, size_var, opts=None,
                 context_name=None, **kwargs):
        self.source_var = Variable(source_var)
        m = size_pat.match(size_var)
        if m:
"""

import sys
import os
import re
from django.db import models
from django.conf import settings
from sorl.thumbnail.main import get_thumbnail_setting

try:
    set
except NameError:
    from sets import Set as set  # For Python 2.3

THUMB_RE = re.compile(r'^%s(.*)_\d{1,}x\d{1,}_[-\w]*q([1-9]\d?|100)\.jpg' %
                      get_thumbnail_setting('PREFIX'))


def get_thumbnail_path(path):
    basedir = get_thumbnail_setting('BASEDIR')
    subdir = get_thumbnail_setting('SUBDIR')
    return os.path.join(basedir, path, subdir)


def clean_up():
    paths = set()
    for app in models.get_apps():
        app_name = app.__name__.split('.')[-2]
        model_list = models.get_models(app)
        for model in model_list:
            for field in model._meta.fields:
Esempio n. 16
0
## Various templatetags for misc stuff
##

# python

# django
from django.utils import simplejson
from django import template
from django.conf import settings

from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.thumbnail.processors import dynamic_import, get_valid_options
thumbnail_processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))

try:
    from django_static import slimfile, staticfile
except ImportError:
    from django_static.templatetags.django_static import slimfile, staticfile
    
from djangopeople.utils import uniqify
MAP_KEYS = settings.MAP_KEYS


register = template.Library()

@register.filter()
def uniqify_on(list_, on):
    return uniqify(list_, lambda x: getattr(x, on))

@register.filter()
def country_flag_src(iso_code):
Esempio n. 17
0
size_pat = re.compile(r"(\d+)x(\d+)$")

filesize_formats = ["k", "M", "G", "T", "P", "E", "Z", "Y"]
filesize_long_formats = {
    "k": "kilo",
    "M": "mega",
    "G": "giga",
    "T": "tera",
    "P": "peta",
    "E": "exa",
    "Z": "zetta",
    "Y": "yotta",
}

try:
    PROCESSORS = dynamic_import(get_thumbnail_setting("PROCESSORS"))
    VALID_OPTIONS = get_valid_options(PROCESSORS)
except:
    if get_thumbnail_setting("DEBUG"):
        raise
    else:
        PROCESSORS = []
        VALID_OPTIONS = []
TAG_SETTINGS = ["quality"]


class ThumbnailNode(Node):
    def __init__(self, source_var, size_var, opts=None, context_name=None, **kwargs):
        self.source_var = source_var
        self.size_var = size_var
        self.opts = opts
Esempio n. 18
0
from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.thumbnail.processors import dynamic_import, get_valid_options
from sorl.thumbnail.utils import split_args

register = Library()

size_pat = re.compile(r'(\d+)x(\d+)$')

filesize_formats = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
filesize_long_formats = {
    'k': 'kilo', 'M': 'mega', 'G': 'giga', 'T': 'tera', 'P': 'peta',
    'E': 'exa', 'Z': 'zetta', 'Y': 'yotta',
}

try:
    PROCESSORS = dynamic_import(get_thumbnail_setting('PROCESSORS'))
    VALID_OPTIONS = get_valid_options(PROCESSORS)
except:
    if get_thumbnail_setting('DEBUG'):
        raise
    else:
        PROCESSORS = []
        VALID_OPTIONS = []
TAG_SETTINGS = ['quality']


class ThumbnailNode(Node):
    def __init__(self, source_var, size_var, opts=None,
                 context_name=None, **kwargs):
        self.source_var = source_var
        self.size_var = size_var
 def mime_type(self):
     extension = get_thumbnail_setting('EXTENSION')
     subtype = 'jpeg' if extension == 'jpg' else extension
     return 'image/%s' % subtype
import os
import re
from django.db import models
from django.conf import settings
from django.core.management.base import NoArgsCommand
from sorl.thumbnail.main import get_thumbnail_setting


try:
    set
except NameError:
    from sets import Set as set     # For Python 2.3

thumb_re = re.compile(r'^%s(.*)_\d{1,}x\d{1,}_[-\w]*q([1-9]\d?|100)\.jpg' %
                      get_thumbnail_setting('PREFIX'))


def get_thumbnail_path(path):
    basedir = get_thumbnail_setting('BASEDIR')
    subdir = get_thumbnail_setting('SUBDIR')
    return os.path.join(basedir, path, subdir)


def clean_up():
    paths = set()
    for app in models.get_apps():
        model_list = models.get_models(app)
        for model in model_list:
            for field in model._meta.fields:
                if isinstance(field, models.ImageField):
                    #TODO: take care of date formatted and callable upload_to.
Esempio n. 21
0
import os
import re
from django.db import models
from django.conf import settings
from django.core.management.base import NoArgsCommand
from sorl.thumbnail.main import get_thumbnail_setting


try:
    set
except NameError:
    from sets import Set as set  # For Python 2.3

thumb_re = re.compile(r"^%s(.*)_\d{1,}x\d{1,}_[-\w]*q([1-9]\d?|100)\.jpg" % get_thumbnail_setting("PREFIX"))


def get_thumbnail_path(path):
    basedir = get_thumbnail_setting("BASEDIR")
    subdir = get_thumbnail_setting("SUBDIR")
    return os.path.join(basedir, path, subdir)


def clean_up():
    paths = set()
    for app in models.get_apps():
        model_list = models.get_models(app)
        for model in model_list:
            for field in model._meta.fields:
                if isinstance(field, models.ImageField):
                    # TODO: take care of date formatted and callable upload_to.
                    if not callable(field.upload_to) and field.upload_to.find("%") == -1:
def get_thumbnail_path(path):
    basedir = get_thumbnail_setting('BASEDIR')
    subdir = get_thumbnail_setting('SUBDIR')
    return os.path.join(basedir, path, subdir)
Esempio n. 23
0
 def mime_type(self):
     extension = get_thumbnail_setting('EXTENSION')
     subtype = 'jpeg' if extension == 'jpg' else extension
     return 'image/%s'  % subtype
Esempio n. 24
0
def thumbnail(url, size='200x200',):
  """
  Given a URL (local or remote) to an image, creates a thumbnailed version of the image, saving
  it locally and then returning the URL to the new, smaller version. If the argument passed is a 
  single integer, like "200", will output a version of the image no larger than 200px wide. If the
  argument passed is two integers, like, "200x300", will output a cropped version of the image that
  is exactly 200px wide by 300px tall (cropped from the center).
  
    {{ story.get_leadphoto_url|thumbnail:"200" }}
    {{ story.get_leadphoto_url|thumbnail:"300x150" }}
  
  This filter is a wrapper around sorl-thumbnail that provides the remote image fetching, as well as
  backwards-compatibility with the previous Savoy thumbnail filter syntax.
  """
  import Image
  import os
  import urllib
  
  if not url == '':
    if not url.startswith(settings.MEDIA_URL):
      # If it's a remote image, download it and save it locally. This expects a
      # directory called img/thumbnailed in your MEDIA_ROOT
      download_filename = url.rsplit('/', 1)[1]                                               # Filename of image
      full_image_path = '%simg/thumbnailed/%s' % (settings.MEDIA_ROOT, download_filename)     # Local filesystem path where image should be saved
      relative_image_path = 'img/thumbnailed/%s' % (download_filename)                        # Path relative to MEDIA_ROOT
      local_image_url = '%simg/thumbnailed/%s' % (settings.MEDIA_URL, download_filename)      # Full URL to local copy of image
      if not os.path.exists(full_image_path):
        unsized_image = urllib.urlretrieve(url)                                               # Fetch original image
        insized_image = os.rename(unsized_image[0], full_image_path)                          # Move the image to the corect path.
      url = local_image_url
    else:
      full_image_path = _get_path_from_url(url)
      relative_image_path = full_image_path[len(settings.MEDIA_ROOT):]

    # Parse the size argument into tuples.
    try:
      # See if both height and width exist (i.e. "200x100")
      desired_width, desired_height = [int(x) for x in size.split('x')]
      new_size = (desired_width, desired_height)
      # Flag this image for cropping, since we want an explicit width AND height.
      crop = True
    except:
      # If only one exists ( i.e. "200"), use the value as the desired width. To do
      # this math, we need the original height of the image, so we must open the image.
      image = Image.open(_get_path_from_url(url))
      desired_width = int(size)
      new_size = (desired_width, image.size[1])
      crop = False
    DEBUG = get_thumbnail_setting('DEBUG')
    try:
      PROCESSORS = dynamic_import(get_thumbnail_setting('PROCESSORS'))
      VALID_OPTIONS = get_valid_options(PROCESSORS)
    except:
      if get_thumbnail_setting('DEBUG'):
        raise
      else:
        PROCESSORS = []
        VALID_OPTIONS = []
    try:
      if crop:
        opts = ['crop']
      else:
        opts = None
      thumbnail = DjangoThumbnail(relative_image_path, new_size, opts=opts, processors=PROCESSORS, **{})
      return thumbnail.absolute_url
    except:
      if DEBUG:
        raise
      else:
        return ''
  else:
    return ''
Esempio n. 25
0
# python
import logging

# django
from django.contrib import admin
from django.utils.translation import get_date_formats
from django.utils import dateformat

from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.thumbnail.processors import dynamic_import, get_valid_options
thumbnail_processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))

# app
from models import KungfuPerson, Club, DiaryEntry, Style, Photo

(date_format, datetime_format, time_format) = get_date_formats()


class KungfuPersonAdmin(admin.ModelAdmin):
    list_display = ('user', 'join_date', 'full_name', 'email', 'profile_views',
                    'mugshot')

    def join_date(self, obj):
        return dateformat.format(obj.user.date_joined, datetime_format)

    def full_name(self, object_):
        return "%s %s" % (object_.user.first_name, object_.user.last_name)

    def email(self, object_):
        return object_.user.email