Example #1
0
def _save_thumbnails(image, original_path, size, suffix):
    # Thumbnail format will be set by original file extension.
    # Use same format to keep transparency of GIF/PNG
    nm = NamedTemporaryFile(suffix='.%s' % image.format)
    default_storage = get_storage_class()()
    try:
        # Ensure conversion to float in operations
        image.thumbnail(get_dimensions(image.size, float(size)), Image.ANTIALIAS)
    except ZeroDivisionError:
        pass
    try:
        image.save(nm.name)
    except IOError:
        # e.g. `IOError: cannot write mode P as JPEG`, which gets raised when
        # someone uploads an image in an indexed-color format like GIF
        image.convert('RGB').save(nm.name)

    # Try to delete file with the same name if it already exists to avoid useless file.
    # i.e if `file_<suffix>.jpg` exists, Storage will save `a_<suffix>_<random_string>.jpg`
    # but nothing in the code is aware about this `<random_string>
    try:
        default_storage.delete(get_path(original_path, suffix))
    except IOError:
        pass

    default_storage.save(
        get_path(original_path, suffix), ContentFile(nm.read()))

    nm.close()
Example #2
0
def image_url(attachment, suffix):
    '''Return url of an image given size(@param suffix)
    e.g large, medium, small, or generate required thumbnail
    '''
    url = attachment.media_file.url
    if suffix == 'original':
        return url
    else:
        default_storage = get_storage_class()()
        fs = get_storage_class('django.core.files.storage.FileSystemStorage')()
        if suffix in settings.THUMB_CONF:
            size = settings.THUMB_CONF[suffix]['suffix']
            filename = attachment.media_file.name
            if default_storage.exists(filename):
                if default_storage.exists(get_path(filename, size)) and\
                        default_storage.size(get_path(filename, size)) > 0:
                    url = default_storage.url(get_path(filename, size))
                else:
                    if default_storage.__class__ != fs.__class__:
                        resize(filename)
                    else:
                        resize_local_env(filename)
                    return image_url(attachment, suffix)
            else:
                return None
    return url
Example #3
0
def image_url(attachment, suffix):
    '''Return url of an image given size(@param suffix)
    e.g large, medium, small, or generate required thumbnail
    '''
    url = attachment.media_file.url

    if suffix == 'original':
        return url
    else:
        default_storage = get_storage_class()()
        fs = get_storage_class('django.core.files.storage.FileSystemStorage')()

        if suffix in settings.THUMB_CONF:
            size = settings.THUMB_CONF[suffix]['suffix']
            filename = attachment.media_file.name

            if default_storage.exists(filename):
                if default_storage.exists(get_path(filename, size)) and\
                        default_storage.size(get_path(filename, size)) > 0:
                    url = default_storage.url(
                        get_path(filename, size))
                else:
                    if default_storage.__class__ != fs.__class__:
                        resize(filename, extension=attachment.extension)
                    else:
                        resize_local_env(filename,
                                         extension=attachment.extension)

                    return image_url(attachment, suffix)
            else:
                return None

    return url
Example #4
0
def _save_thumbnails(image, path, size, suffix):
    nm = NamedTemporaryFile(suffix='.%s' % image.format)
    default_storage = get_storage_class()()
    try:
        # Ensure conversion to float in operations
        # Converting to RGBA make the background white instead of black for
        # transparent PNGs/GIFs
        image = image.convert("RGBA")
        image.thumbnail(get_dimensions(image.size, float(size)), Image.ANTIALIAS)
    except ZeroDivisionError:
        pass
    try:
        image.save(nm.name)
    except IOError:
        # e.g. `IOError: cannot write mode P as JPEG`, which gets raised when
        # someone uploads an image in an indexed-color format like GIF
        image.convert('RGB').save(nm.name)

    # Try to delete file with the same name if it already exists to avoid useless file.
    # i.e if `file_<suffix>.jpg` exists, Storage will save `a_<suffix>_<random_string>.jpg`
    # but nothing in the code is aware about this `<random_string>
    try:
        default_storage.delete(get_path(path, suffix))
    except IOError:
        pass

    default_storage.save(
        get_path(path, suffix), ContentFile(nm.read()))

    nm.close()
 def handle(self, *args, **options):
     attachments_qs = Attachment.objects.select_related(
         'instance', 'instance__xform')
     if options.get('username'):
         username = options.get('username')
         try:
             user = User.objects.get(username=username)
         except User.DoesNotExist:
             raise CommandError(
                 "Error: username %(username)s does not exist" %
                 {'username': username})
         attachments_qs = attachments_qs.filter(instance__user=user)
     if options.get('id_string'):
         id_string = options.get('id_string')
         try:
             xform = XForm.objects.get(id_string=id_string)
         except XForm.DoesNotExist:
             raise CommandError(
                 "Error: Form with id_string %(id_string)s does not exist" %
                 {'id_string': id_string})
         attachments_qs = attachments_qs.filter(instance__xform=xform)
     fs = get_storage_class('django.core.files.storage.FileSystemStorage')()
     for att in queryset_iterator(attachments_qs):
         filename = att.media_file.name
         default_storage = get_storage_class()()
         full_path = get_path(filename,
                              settings.THUMB_CONF['small']['suffix'])
         if options.get('force') is not None:
             for s in ['small', 'medium', 'large']:
                 fp = get_path(filename, settings.THUMB_CONF[s]['suffix'])
                 if default_storage.exists(fp):
                     default_storage.delete(fp)
         if not default_storage.exists(full_path):
             try:
                 if default_storage.__class__ != fs.__class__:
                     resize(filename, att.extension)
                 else:
                     resize_local_env(filename, att.extension)
                 path = get_path(filename,
                                 '%s' % THUMB_CONF['small']['suffix'])
                 if default_storage.exists(path):
                     self.stdout.write(
                         _(u'Thumbnails created for %(file)s') %
                         {'file': filename})
                 else:
                     self.stdout.write(
                         _(u'Problem with the file %(file)s') %
                         {'file': filename})
             except (IOError, OSError) as e:
                 self.stderr.write(
                     _(u'Error on %(filename)s: %(error)s') % {
                         'filename': filename,
                         'error': e
                     })
    def handle(self, *args, **kwargs):
        attachments_qs = Attachment.objects.select_related(
            'instance', 'instance__xform')
        if kwargs.get('username'):
            username = kwargs.get('username')
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                raise CommandError(
                    "Error: username %(username)s does not exist" %
                    {'username': username})
            attachments_qs = attachments_qs.filter(instance__user=user)
        if kwargs.get('id_string'):
            id_string = kwargs.get('id_string')
            try:
                xform = XForm.objects.get(id_string=id_string)
            except XForm.DoesNotExist:
                raise CommandError(
                    "Error: Form with id_string %(id_string)s does not exist" %
                    {'id_string': id_string})
            attachments_qs = attachments_qs.filter(instance__xform=xform)

        for att in queryset_iterator(attachments_qs):
            filename = att.media_file.name
            default_storage = get_storage_class()()
            full_path = get_path(filename,
                                 settings.THUMB_CONF['small']['suffix'])
            if kwargs.get('force') is not None:
                for s in settings.THUMB_CONF.keys():
                    fp = get_path(filename, settings.THUMB_CONF[s]['suffix'])
                    if default_storage.exists(fp):
                        default_storage.delete(fp)

            if not default_storage.exists(full_path):
                try:
                    resize(filename)
                    if default_storage.exists(
                            get_path(
                                filename, '%s' %
                                settings.THUMB_CONF['small']['suffix'])):
                        print(
                            _('Thumbnails created for %(file)s') %
                            {'file': filename})
                    else:
                        print(
                            _('Problem with the file %(file)s') %
                            {'file': filename})
                except (IOError, OSError), e:
                    print(
                        _('Error on %(filename)s: %(error)s') % {
                            'filename': filename,
                            'error': e
                        })
Example #7
0
 def handle(self, *args, **options):
     attachments_qs = Attachment.objects.select_related(
         'instance', 'instance__xform')
     if options.get('username'):
         username = options.get('username')
         try:
             user = User.objects.get(username=username)
         except User.DoesNotExist:
             raise CommandError(
                 "Error: username %(username)s does not exist" %
                 {'username': username})
         attachments_qs = attachments_qs.filter(instance__user=user)
     if options.get('id_string'):
         id_string = options.get('id_string')
         try:
             xform = XForm.objects.get(id_string=id_string)
         except XForm.DoesNotExist:
             raise CommandError(
                 "Error: Form with id_string %(id_string)s does not exist" %
                 {'id_string': id_string})
         attachments_qs = attachments_qs.filter(instance__xform=xform)
     fs = get_storage_class('django.core.files.storage.FileSystemStorage')()
     for att in queryset_iterator(attachments_qs):
         filename = att.media_file.name
         default_storage = get_storage_class()()
         full_path = get_path(filename,
                              settings.THUMB_CONF['small']['suffix'])
         if options.get('force') is not None:
             for s in ['small', 'medium', 'large']:
                 fp = get_path(filename, settings.THUMB_CONF[s]['suffix'])
                 if default_storage.exists(fp):
                     default_storage.delete(fp)
         if not default_storage.exists(full_path):
             try:
                 if default_storage.__class__ != fs.__class__:
                     resize(filename, att.extension)
                 else:
                     resize_local_env(filename, att.extension)
                 path = get_path(
                     filename, '%s' % THUMB_CONF['small']['suffix'])
                 if default_storage.exists(path):
                     self.stdout.write(
                         _(u'Thumbnails created for %(file)s') %
                         {'file': filename})
                 else:
                     self.stdout.write(
                         _(u'Problem with the file %(file)s') %
                         {'file': filename})
             except (IOError, OSError) as e:
                 self.stderr.write(_(
                     u'Error on %(filename)s: %(error)s')
                     % {'filename': filename, 'error': e})
Example #8
0
def get_attachment_data(attachment, suffix):
    if suffix in list(settings.THUMB_CONF):
        image_url(attachment, suffix)
        suffix = settings.THUMB_CONF.get(suffix).get('suffix')
        f = default_storage.open(get_path(attachment.media_file.name, suffix))
        data = f.read()
    else:
        data = attachment.media_file.read()

    return data
def get_attachment_data(attachment, suffix):
    if suffix in settings.THUMB_CONF.keys():
        image_url(attachment, suffix)
        suffix = settings.THUMB_CONF.get(suffix).get('suffix')
        f = default_storage.open(
            get_path(attachment.media_file.name, suffix))
        data = f.read()
    else:
        data = attachment.media_file.read()

    return data
Example #10
0
def _save_thumbnails(image, path, size, suffix):
    nm = NamedTemporaryFile(suffix='.%s' % settings.IMG_FILE_TYPE)
    default_storage = get_storage_class()()
    try:
        # Ensure conversion to float in operations
        image.thumbnail(get_dimensions(image.size, float(size)),
                        Image.ANTIALIAS)
    except ZeroDivisionError:
        pass
    image.save(nm.name)
    default_storage.save(get_path(path, suffix), ContentFile(nm.read()))
    nm.close()
Example #11
0
def _save_thumbnails(image, path, size, suffix):
    nm = NamedTemporaryFile(suffix='.%s' % settings.IMG_FILE_TYPE)
    default_storage = get_storage_class()()
    try:
        # Ensure conversion to float in operations
        image.thumbnail(
            get_dimensions(image.size, float(size)), Image.ANTIALIAS)
    except ZeroDivisionError:
        pass
    image.save(nm.name)
    default_storage.save(
        get_path(path, suffix), ContentFile(nm.read()))
    nm.close()
Example #12
0
def image_url(attachment, suffix):
    """
    Return url of an image given size(@param suffix)
    e.g large, medium, small, or generate required thumbnail
    """
    url = attachment.media_file.url
    if suffix == 'original':
        return url
    else:
        default_storage = get_storage_class()()
        if suffix in settings.THUMB_CONF:
            size = settings.THUMB_CONF[suffix]['suffix']
            filename = attachment.media_file.name
            if default_storage.exists(filename):
                if default_storage.exists(get_path(filename, size)) and \
                        default_storage.size(get_path(filename, size)) > 0:
                    url = default_storage.url(get_path(filename, size))
                else:
                    resize(filename)
                    return image_url(attachment, suffix)
            else:
                return None
    return url
Example #13
0
def _save_thumbnails(image, path, size, suffix):
    nm = NamedTemporaryFile(suffix='.%s' % settings.IMG_FILE_TYPE)
    default_storage = get_storage_class()()
    try:
        # Ensure conversion to float in operations
        image.thumbnail(get_dimensions(image.size, float(size)),
                        Image.ANTIALIAS)
    except ZeroDivisionError:
        pass
    try:
        image.save(nm.name)
    except IOError:
        # e.g. `IOError: cannot write mode P as JPEG`, which gets raised when
        # someone uploads an image in an indexed-color format like GIF
        image.convert('RGB').save(nm.name)
    default_storage.save(get_path(path, suffix), ContentFile(nm.read()))
    nm.close()
Example #14
0
def _save_thumbnails(image, path, size, suffix):
    nm = NamedTemporaryFile(suffix='.%s' % settings.IMG_FILE_TYPE)
    default_storage = get_storage_class()()
    try:
        # Ensure conversion to float in operations
        image.thumbnail(
            get_dimensions(image.size, float(size)), Image.ANTIALIAS)
    except ZeroDivisionError:
        pass
    try:
        image.save(nm.name)
    except IOError:
        # e.g. `IOError: cannot write mode P as JPEG`, which gets raised when
        # someone uploads an image in an indexed-color format like GIF
        image.convert('RGB').save(nm.name)
    default_storage.save(
        get_path(path, suffix), ContentFile(nm.read()))
    nm.close()