Пример #1
0
 def test_partial_target(self):
     self.assertEqual(
         aliases.get('banner', target='some_app.Profile.avatar'),
         {'size': (600, 80), 'crop': True})
     self.assertEqual(aliases.get('banner', target='some_app.Profile'),
         {'size': (600, 80), 'crop': True})
     self.assertEqual(aliases.get('banner', target='some_app'), None)
Пример #2
0
 def test_target_fallback(self):
     # Unknown target.
     self.assertEqual(aliases.get("small", target="some_app.Profile.not_avatar"), {"size": (100, 100)})
     # Known target with no matching alias (but a matching global alias).
     self.assertEqual(aliases.get("medium", target="some_app.Profile.avatar"), {"size": (300, 300)})
     # Known target with no matching alias.
     self.assertEqual(aliases.get("invalid", target="some_app.Profile.avatar"), None)
Пример #3
0
 def test_target(self):
     self.assertEqual(
         aliases.get('avatar', target='some_app.Profile.avatar'),
         {'size': (80, 80), 'crop': True})
     self.assertEqual(
         aliases.get('small', target='some_app.Profile.avatar'),
         {'size': (20, 20), 'crop': True})
Пример #4
0
 def test_target(self):
     self.assertEqual(
         aliases.get(
             'avatar', target='easy_thumbnails_tests.Profile.avatar'),
         {'size': (80, 80), 'crop': True})
     self.assertEqual(
         aliases.get(
             'small', target='easy_thumbnails_tests.Profile.avatar'),
         {'size': (20, 20), 'crop': True})
Пример #5
0
 def test_partial_target(self):
     self.assertEqual(
         aliases.get(
             'banner', target='easy_thumbnails_tests.Profile.avatar'),
         {'size': (600, 80), 'crop': True})
     self.assertEqual(
         aliases.get('banner', target='easy_thumbnails_tests.Profile'),
         {'size': (600, 80), 'crop': True})
     self.assertEqual(
         aliases.get('banner', target='easy_thumbnails_tests'), None)
Пример #6
0
    def dehydrate(self, bundle):
        '''
        Also send the URLs for the thumbnailed pictures
        '''
        thumbnails = {}
        for alias in aliases.all():
            t = get_thumbnailer(bundle.obj.image)
            thumbnails[alias] = {'url': t.get_thumbnail(aliases.get(alias)).url,
                                 'settings': aliases.get(alias)}

        bundle.data['thumbnails'] = thumbnails
        return bundle
Пример #7
0
 def test_target_fallback(self):
     # Unknown target.
     self.assertEqual(
         aliases.get('small', target='some_app.Profile.not_avatar'),
         {'size': (100, 100)})
     # Known target with no matching alias (but a matching global alias).
     self.assertEqual(
         aliases.get('medium', target='some_app.Profile.avatar'),
         {'size': (300, 300)})
     # Known target with no matching alias.
     self.assertEqual(
         aliases.get('invalid', target='some_app.Profile.avatar'), None)
Пример #8
0
 def thumbnails(self, request, pk):
     '''
     Return a list of the image's thumbnails
     '''
     image = ExerciseImage.objects.get(pk=pk)
     thumbnails = {}
     for alias in aliases.all():
         t = get_thumbnailer(image.image)
         thumbnails[alias] = {'url': t.get_thumbnail(aliases.get(alias)).url,
                              'settings': aliases.get(alias)}
     thumbnails['original'] = image.image.url
     return Response(thumbnails)
Пример #9
0
 def test_target(self):
     self.assertEqual(
         aliases.get('avatar',
                     target='easy_thumbnails_tests.Profile.avatar'), {
                         'size': (80, 80),
                         'crop': True
                     })
     self.assertEqual(
         aliases.get('small',
                     target='easy_thumbnails_tests.Profile.avatar'), {
                         'size': (20, 20),
                         'crop': True
                     })
Пример #10
0
 def test_target_fallback(self):
     # Unknown target.
     self.assertEqual(
         aliases.get('small', target='some_app.Profile.not_avatar'),
         {'size': (100, 100)})
     # Known target with no matching alias (but a matching global alias).
     self.assertEqual(
         aliases.get('medium', target='some_app.Profile.avatar'),
         {'size': (300, 300)})
     # Known target with no matching alias.
     self.assertEqual(
         aliases.get('invalid', target='some_app.Profile.avatar'),
         None)
Пример #11
0
    def dehydrate(self, bundle):
        """
        Also send the URLs for the thumbnailed pictures
        """
        thumbnails = {}
        for alias in aliases.all():
            t = get_thumbnailer(bundle.obj.image)
            thumbnails[alias] = {
                'url': t.get_thumbnail(aliases.get(alias)).url,
                'settings': aliases.get(alias)
            }

        bundle.data['thumbnails'] = thumbnails
        return bundle
Пример #12
0
 def test_partial_target(self):
     self.assertEqual(
         aliases.get('banner',
                     target='easy_thumbnails_tests.Profile.avatar'), {
                         'size': (600, 80),
                         'crop': True
                     })
     self.assertEqual(
         aliases.get('banner', target='easy_thumbnails_tests.Profile'), {
             'size': (600, 80),
             'crop': True
         })
     self.assertEqual(aliases.get('banner', target='easy_thumbnails_tests'),
                      None)
Пример #13
0
 def thumbnails(self, request, pk):
     '''
     Return a list of the image's thumbnails
     '''
     image = ExerciseImage.objects.get(pk=pk)
     thumbnails = {}
     for alias in aliases.all():
         t = get_thumbnailer(image.image)
         thumbnails[alias] = {
             'url': t.get_thumbnail(aliases.get(alias)).url,
             'settings': aliases.get(alias)
         }
     thumbnails['original'] = image.image.url
     return Response(thumbnails)
Пример #14
0
    def retina_upscale(file: FilerImage, alias: Optional[str] = None, density: Optional[int] = 1) -> list:
        thumbnailer = get_thumbnailer(file)

        # We need to manually raise a KeyError since the get function can return None
        options = dict(aliases.get(alias))
        if not options:
            raise KeyError(alias)

        # Support for subject_location. This only works if scale_and_crop_with_subject_location is in
        # the THUMBNAIL_PROCESSORS and crop in the given alias is True
        if getattr(file, 'subject_location', None):
            options.update({'subject_location': file.subject_location})

        files = [thumbnailer.get_thumbnail(options).url]

        # Throws AttributeError if no size defined so make sure this property is set in your thumbnail alias
        original_size = options['size']

        for i in range(1, density):
            # Create a copy of the options since we're multiplying the size values bellow and
            # don't want to change the original ones
            new_options = options.copy()
            new_options.update({'size': tuple(size * (i + 1) for size in original_size)})

            files.append(thumbnailer.get_thumbnail(new_options).url)

        return files
Пример #15
0
 def thumbnail_field(self, obj):
     field = obj._meta.get_field(field_name)
     field_value = getattr(obj, field_name)
     if not field_value:
         return ''
     ''' determine the image url based on the field type - in the case
         of `ThumbnailerImageField` instances, check the alias given
         against the list of available aliases from `easy_thumbnails`
     '''
     if (ThumbnailerImageField
             and isinstance(field, ThumbnailerImageField)
             and aliases.get(alias)):
         url = field_value[alias].url
     elif isinstance(field, FileField):
         url = field_value.url
     else:
         raise TypeError(
             'admin_thumbnails: Specified field must be an instance of '
             'Django’s `ImageField`, `FileField` or easy_thumbnails’ '
             '`ThumbnailerImageField` (received: {0})'.format(
                 field.get_internal_name()))
     ''' generate styles and build <img> tag '''
     style = dict(ADMIN_THUMBNAIL_STYLE)
     if background:
         style.update(ADMIN_THUMBNAIL_BACKGROUND_STYLE)
     return mark_safe(
         '<img src="{0}" style="{1}" alt="Thumbnail">'.format(
             url, unpack_styles(style)))
Пример #16
0
def thumbnail(source, alias=None, generate=True, **kwargs):
    if not source:
        return None

    cache_key, cached_thumbnail_url = _get_cached_thumbnail_url(
        source, alias=alias, generate=generate, **kwargs)

    if cached_thumbnail_url is not None:
        return cached_thumbnail_url

    thumbnailer_instance = get_thumbnailer(source)

    if not thumbnailer_instance:
        return None

    if _is_svg(thumbnailer_instance):
        return source.url if hasattr(source, 'url') else None

    if alias:
        options = aliases.get(alias, target=thumbnailer_instance.alias_target)
        options.update(process_thumbnailer_options(kwargs))
    else:
        options = process_thumbnailer_options(kwargs)

    try:
        thumbnail_instance = thumbnailer_instance.get_thumbnail(
            options, generate=generate)
        thumbnail_url = thumbnail_instance.url
        if cache_key:
            cache.set(cache_key, thumbnail_url)
        return thumbnail_url
    except (IOError, InvalidImageFormatError, ValueError):
        return None
Пример #17
0
 def test_deferred(self):
     loading.cache.loaded = False
     deferred_profile = deferred_class_factory(models.Profile, ('logo',))
     instance = deferred_profile(avatar='avatars/test.jpg')
     self.assertEqual(
         aliases.get('small', target=instance.avatar),
         {'size': (20, 20), 'crop': True})
Пример #18
0
def thumbnail(source, alias=None, generate=True, **kwargs):
    if not source:
        return None

    cache_key, cached_thumbnail_url = _get_cached_thumbnail_url(source, alias=alias, generate=generate, **kwargs)

    if cached_thumbnail_url is not None:
        return cached_thumbnail_url

    thumbnailer_instance = get_thumbnailer(source)

    if not thumbnailer_instance:
        return None

    if _is_svg(thumbnailer_instance):
        return source.url if hasattr(source, 'url') else None

    if alias:
        options = aliases.get(alias, target=thumbnailer_instance.alias_target)
        options.update(process_thumbnailer_options(kwargs))
    else:
        options = process_thumbnailer_options(kwargs)

    try:
        thumbnail_instance = thumbnailer_instance.get_thumbnail(options, generate=generate)
        thumbnail_url = thumbnail_instance.url
        if cache_key:
            cache.set(cache_key, thumbnail_url)
        return thumbnail_url
    except (IOError, InvalidImageFormatError, ValueError):
        return None
Пример #19
0
 def test_deferred(self):
     loading.cache.loaded = False
     deferred_profile = deferred_class_factory(models.Profile, ('logo', ))
     instance = deferred_profile(avatar='avatars/test.jpg')
     self.assertEqual(aliases.get('small', target=instance.avatar), {
         'size': (20, 20),
         'crop': True
     })
Пример #20
0
 def picture_print(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             return thumbnailer.get_thumbnail(aliases.get('print'))
         except InvalidImageFormatError:
             logger.warning(_("Image %s invalid or missing from disk.") % picture.attachment_file)
     return None
Пример #21
0
 def thumbnail(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             return thumbnailer.get_thumbnail(aliases.get('small-square'))
         except InvalidImageFormatError:
             logger.error(_("Image %s invalid or missing from disk.") % picture.attachment_file)
     return None
Пример #22
0
 def thumbnail(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             return thumbnailer.get_thumbnail(aliases.get('small-square'))
         except InvalidImageFormatError:
             logger.warning(_("Image %s invalid or missing from disk.") % picture.attachment_file)
     return None
Пример #23
0
    def get_context_data(self, **kwargs):
        context = super(CompetitionDetail, self).get_context_data(**kwargs)
        context.update(
            {'news_list': News.objects.published(self.object.get_ids())[:3]})

        if self.object.level == 2:
            calendar = Competition.objects.filter(
                parent_id=self.object.parent_id)
        else:
            children = self.object.get_children()
            if children:
                calendar = children
            else:
                calendar = [
                    self.object,
                ]
        context.update({'calendar': calendar})

        # Showing 6 albums from current type of competition, first showing albums from current competition
        cache_key = 'competition_detail_albums_%i' % self.competition.id
        albums = cache.get(cache_key, None)
        if albums is None:
            albums_query = Album.objects.filter(
                competition__tree_id=self.object.tree_id,
                is_processed=True).extra(select={
                    'is_current':
                    "CASE WHEN competition_id = %s Then true ELSE false END"
                },
                                         select_params=(
                                             self.object.id, )).order_by(
                                                 '-is_current',
                                                 '-gallery_date', '-id')[:6]
            try:
                albums = [(obj.id,
                           obj.primary_image.image.get_thumbnail(
                               aliases.get('thumb',
                                           target=obj.primary_image.image),
                               silent_template_exception=True).url)
                          for obj in albums_query]
                cache.set(cache_key, albums)
            except InvalidImageFormatError:
                albums = []
        context.update({'galleries': albums})

        # Showing latest featured video in current/parent competition
        cache_key = 'competition_detail_video_%i' % self.competition.id
        video = cache.get(cache_key, None)
        if video is None:
            try:
                video = Video.objects.filter(competition_id__in=self.object.get_ids()) \
                    .filter(status=1, is_featured=True).order_by('-id')[0].url_embed
                cache.set(cache_key, video)
            except IndexError:
                cache.set(cache_key, False)
                video = None
        context.update({'video': video})

        return context
Пример #24
0
 def get_thumbnail(self, obj):
     thumbnailer = get_thumbnailer(obj.attachment_file)
     try:
         thumbnail = thumbnailer.get_thumbnail(aliases.get('small-square'))
     except (IOError, InvalidImageFormatError, DecompressionBombError):
         return ""
     thumbnail.author = obj.author
     thumbnail.legend = obj.legend
     return build_url(self, thumbnail.url)
Пример #25
0
 def thumbnail(self):
     if not self.photo:
         return None
     thumbnailer = get_thumbnailer(self.photo)
     try:
         return thumbnailer.get_thumbnail(aliases.get('thumbnail'))
     except InvalidImageFormatError:
         logger.warning(_("Image %s invalid or missing from disk.") % self.photo)
         return None
Пример #26
0
 def _load_aliases():
     try:
         from cmsplugin_filer_image.models import ThumbnailOption
     except ImportError:
         from filer.models import ThumbnailOption
     thumbs = ThumbnailOption.objects.all()
     for thumb in thumbs:
         if not aliases.get(thumb.name):
             aliases.set(thumb.name, thumb.as_dict)
Пример #27
0
 def resized_picture(self):
     if not self.photo:
         return None
     thumbnailer = get_thumbnailer(self.photo)
     try:
         return thumbnailer.get_thumbnail(aliases.get('medium'))
     except (IOError, InvalidImageFormatError):
         logger.warning(_("Image %s invalid or missing from disk.") % self.photo)
         return None
Пример #28
0
 def thumbnail(self):
     if not self.photo:
         return None
     thumbnailer = get_thumbnailer(self.photo)
     try:
         return thumbnailer.get_thumbnail(aliases.get('thumbnail'))
     except InvalidImageFormatError:
         logger.error(_("Image %s invalid or missing from disk.") % self.photo)
         return None
Пример #29
0
 def __getitem__(self, alias):
     """
     Retrieve a thumbnail matching the alias options (or raise a
     ``KeyError`` if no such alias exists).
     """
     options = aliases.get(alias, target=self.alias_target)
     if not options:
         raise KeyError(alias)
     return self.get_thumbnail(options, silent_template_exception=True)
Пример #30
0
    def thumbnails(self, request, pk):
        """
        Return a list of the image's thumbnails
        """
        try:
            image = ExerciseImage.objects.get(pk=pk)
        except ExerciseImage.DoesNotExist:
            return Response([])

        thumbnails = {}
        for alias in aliases.all():
            t = get_thumbnailer(image.image)
            thumbnails[alias] = {
                'url': t.get_thumbnail(aliases.get(alias)).url,
                'settings': aliases.get(alias)
            }
        thumbnails['original'] = image.image.url
        return Response(thumbnails)
Пример #31
0
 def __getitem__(self, alias):
     """
     Retrieve a thumbnail matching the alias options (or raise a
     ``KeyError`` if no such alias exists).
     """
     options = aliases.get(alias, target=self.alias_target)
     if not options:
         raise KeyError(alias)
     return self.get_thumbnail(options, silent_template_exception=True)
Пример #32
0
 def picture_print(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             return thumbnailer.get_thumbnail(aliases.get('print'))
         except InvalidImageFormatError:
             logger.error(
                 _("Image %s invalid or missing from disk.") %
                 picture.attachment_file)
     return None
Пример #33
0
 def resized_pictures(self):
     resized = []
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             thdetail = thumbnailer.get_thumbnail(aliases.get('medium'))
         except InvalidImageFormatError:
             logger.error(_("Image %s invalid or missing from disk.") % picture.attachment_file)
         resized.append((picture, thdetail))
     return resized
Пример #34
0
 def resized_pictures(self):
     resized = []
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             thdetail = thumbnailer.get_thumbnail(aliases.get('medium'))
         except InvalidImageFormatError:
             logger.info(_("Image %s invalid or missing from disk.") % picture.attachment_file)
         else:
             resized.append((picture, thdetail))
     return resized
Пример #35
0
 def photo_url(self):
     if not self.photo:
         return None
     thumbnailer = get_thumbnailer(self.photo)
     try:
         thumb_detail = thumbnailer.get_thumbnail(aliases.get('thumbnail'))
         thumb_url = os.path.join(settings.MEDIA_URL, thumb_detail.name)
     except InvalidImageFormatError:
         thumb_url = None
         logger.error(_("Image %s invalid or missing from disk.") % self.photo)
     return thumb_url
Пример #36
0
 def serializable_pictures(self):
     serialized = []
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         thdetail = thumbnailer.get_thumbnail(aliases.get('medium'))
         serialized.append({
             'author': picture.author,
             'title': picture.title,
             'legend': picture.legend,
             'url': os.path.join(settings.MEDIA_URL, thdetail.name)
         })
     return serialized
Пример #37
0
 def thumbnail(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             thumbnail = thumbnailer.get_thumbnail(aliases.get('small-square'))
         except (IOError, InvalidImageFormatError, DecompressionBombError) as e:
             logger.info(_("Image {} invalid or missing from disk: {}.").format(picture.attachment_file, e))
             continue
         thumbnail.author = picture.author
         thumbnail.legend = picture.legend
         return thumbnail
     return None
Пример #38
0
 def thumbnail(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             thumbnail = thumbnailer.get_thumbnail(aliases.get('small-square'))
         except (IOError, InvalidImageFormatError):
             logger.info(_("Image %s invalid or missing from disk.") % picture.attachment_file)
             continue
         thumbnail.author = picture.author
         thumbnail.legend = picture.legend
         return thumbnail
     return None
Пример #39
0
    def to_native(self, value):
        if value:
            try:
                thumb = value.get_thumbnail(aliases.get(self.thumbnail_alias),
                                            generate=self.force_generate)

                url = thumb.url if thumb else value.url
                return self.get_absoulute_url(url)
            except Exception:  # pragma: nocover
                logger.exception('Error getting image thumbnail')

        return super(CroppedImageURLField, self).to_native(value)
Пример #40
0
 def thumbnail(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             thumbnail = thumbnailer.get_thumbnail(aliases.get('small-square'))
         except InvalidImageFormatError:
             logger.info(_("Image %s invalid or missing from disk.") % picture.attachment_file)
             continue
         thumbnail.author = picture.author
         thumbnail.legend = picture.legend
         return thumbnail
     return None
Пример #41
0
 def photo_url(self):
     if not self.photo:
         return None
     thumbnailer = get_thumbnailer(self.photo)
     try:
         thumb_detail = thumbnailer.get_thumbnail(aliases.get('thumbnail'))
         thumb_url = os.path.join(settings.MEDIA_URL, thumb_detail.name)
     except InvalidImageFormatError:
         thumb_url = None
         logger.error(
             _("Image %s invalid or missing from disk.") % self.photo)
     return thumb_url
Пример #42
0
 def serializable_pictures(self):
     serialized = []
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         thdetail = thumbnailer.get_thumbnail(aliases.get("medium"))
         serialized.append(
             {
                 "author": picture.author,
                 "title": picture.title,
                 "legend": picture.legend,
                 "url": os.path.join(settings.MEDIA_URL, thdetail.name),
             }
         )
     return serialized
Пример #43
0
 def serializable_pictures(self):
     serialized = []
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         thdetail = thumbnailer.get_thumbnail(aliases.get('medium'))
         serialized.append({
             'author':
             picture.author,
             'title':
             picture.title,
             'legend':
             picture.legend,
             'url':
             os.path.join(settings.MEDIA_URL, thdetail.name)
         })
     return serialized
Пример #44
0
 def serializable_pictures(self):
     serialized = []
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             thdetail = thumbnailer.get_thumbnail(aliases.get('medium'))
             thurl = os.path.join(settings.MEDIA_URL, thdetail.name)
         except InvalidImageFormatError:
             thurl = None
             logger.error(_("Image %s invalid or missing from disk.") % picture.attachment_file)
             pass
         serialized.append({
             'author': picture.author,
             'title': picture.title,
             'legend': picture.legend,
             'url': thurl
         })
     return serialized
Пример #45
0
def thumbnail(request, alias, path):
    '''Redirect to a thumbnail as configured with GET params'''

    # Clean up path
    path = os.path.normpath(path)
    # Unescape
    path = unquote(path)

    options = aliases.get(alias)

    # Create thumbnail
    try:
        thumbnail = get_thumbnailer(path).get_thumbnail(options)

        return http.HttpResponsePermanentRedirect(thumbnail.url)

    except EasyThumbnailsError:
        raise http.Http404
Пример #46
0
def thumbnail(source, alias=None, generate=True, **kwargs):
    if not source:  # pragma: no cover
        return None
    thumbnailer = get_thumbnailer(source)
    if not thumbnailer:  # pragma: no cover
        return None

    if alias:
        options = aliases.get(alias, target=thumbnailer.alias_target)
        options.update(process_thumbnailer_options(kwargs))
    else:
        options = process_thumbnailer_options(kwargs)

    try:
        thumbnail = thumbnailer.get_thumbnail(options, generate=generate)
        return thumbnail.url
    except InvalidImageFormatError:  # pragma: no cover
        pass
Пример #47
0
def thumbnail(request, alias, path):
    '''Redirect to a thumbnail as configured with GET params'''

    # Clean up path
    path = os.path.normpath(path)
    # Unescape
    path = unquote(path)

    options = aliases.get(alias)

    # Create thumbnail
    try:
        thumbnail = get_thumbnailer(path).get_thumbnail(options)

        return http.HttpResponsePermanentRedirect(thumbnail.url)

    except EasyThumbnailsError:
        raise http.Http404
Пример #48
0
def search(request):
    """
    Searches for exercises.

    This format is currently used by the exercise search autocompleter
    """
    q = request.GET.get('term', None)
    results = []
    json_response = {}

    if q:
        languages = load_item_languages(
            LanguageConfig.SHOW_ITEM_EXERCISES, language_code=request.GET.get('language', None)
        )
        exercises = (
            Exercise.objects.filter(name__icontains=q).filter(language__in=languages).filter(
                status=Exercise.STATUS_ACCEPTED
            ).order_by('exercise_base__category__name', 'name').distinct()
        )

        for exercise in exercises:
            if exercise.main_image:
                image_obj = exercise.main_image
                image = image_obj.image.url
                t = get_thumbnailer(image_obj.image)
                thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url
            else:
                image = None
                thumbnail = None

            exercise_json = {
                'value': exercise.name,
                'data': {
                    'id': exercise.id,
                    'name': exercise.name,
                    'category': _(exercise.category.name),
                    'image': image,
                    'image_thumbnail': thumbnail
                }
            }
            results.append(exercise_json)
        json_response['suggestions'] = results

    return Response(json_response)
Пример #49
0
def search(request):
    '''
    Searches for exercises.

    This format is currently used by the exercise search autocompleter
    '''
    q = request.GET.get('term', None)
    results = []
    json_response = {}

    if q:
        languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES,
                                        language_code=request.GET.get('language', None))
        exercises = (Exercise.objects.filter(name__icontains=q)
                     .filter(language__in=languages)
                     .filter(status=Exercise.STATUS_ACCEPTED)
                     .order_by('category__name', 'name')
                     .distinct())

        for exercise in exercises:
            if exercise.main_image:
                image_obj = exercise.main_image
                image = image_obj.image.url
                t = get_thumbnailer(image_obj.image)
                thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url
            else:
                image = None
                thumbnail = None

            exercise_json = {
                'value': exercise.name,
                'data': {
                    'id': exercise.id,
                    'name': exercise.name,
                    'category': _(exercise.category.name),
                    'image': image,
                    'image_thumbnail': thumbnail
                }
            }
            results.append(exercise_json)
        json_response['suggestions'] = results

    return Response(json_response)
Пример #50
0
 def serializable_pictures(self):
     serialized = []
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         try:
             thdetail = thumbnailer.get_thumbnail(aliases.get('medium'))
             thurl = os.path.join(settings.MEDIA_URL, thdetail.name)
         except InvalidImageFormatError:
             thurl = None
             logger.error(
                 _("Image %s invalid or missing from disk.") %
                 picture.attachment_file)
             pass
         serialized.append({
             'author': picture.author,
             'title': picture.title,
             'legend': picture.legend,
             'url': thurl
         })
     return serialized
Пример #51
0
def thumbnail(source, alias=None, generate=True, **kwargs):
    if not source:
        return None
    thumbnailer = get_thumbnailer(source)
    if not thumbnailer:
        return None

    if _is_svg(thumbnailer.file):
        return source.url if hasattr(source, 'url') else None

    if alias:
        options = aliases.get(alias, target=thumbnailer.alias_target)
        options.update(process_thumbnailer_options(kwargs))
    else:
        options = process_thumbnailer_options(kwargs)

    try:
        thumbnail = thumbnailer.get_thumbnail(options, generate=generate)
        return thumbnail.url
    except (IOError, InvalidImageFormatError):
        return None
Пример #52
0
def thumbnail(source, alias=None, generate=True, **kwargs):
    if not source:
        return None
    thumbnailer = get_thumbnailer(source)
    if not thumbnailer:
        return None

    if _is_svg(thumbnailer.file):
        return source.url if hasattr(source, 'url') else None

    if alias:
        options = aliases.get(alias, target=thumbnailer.alias_target)
        options.update(process_thumbnailer_options(kwargs))
    else:
        options = process_thumbnailer_options(kwargs)

    try:
        thumbnail = thumbnailer.get_thumbnail(options, generate=generate)
        return thumbnail.url
    except (IOError, InvalidImageFormatError):
        return None
Пример #53
0
def search(request):
    '''
    Search an exercise, return the result as a JSON list
    '''

    # Perform the search
    q = request.GET.get('term', '')

    languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)
    exercises = (Exercise.objects.filter(name__icontains=q)
                                 .filter(language__in=languages)
                                 .filter(status__in=Exercise.EXERCISE_STATUS_OK)
                                 .order_by('category__name', 'name')
                                 .distinct())

    results = []
    for exercise in exercises:
        if exercise.exerciseimage_set.exists():
            image_obj = exercise.exerciseimage_set.filter(is_main=True)[0]
            image = image_obj.image.url
            t = get_thumbnailer(image_obj.image)
            thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url
        else:
            image = None
            thumbnail = None

        exercise_json = {}
        exercise_json['id'] = exercise.id
        exercise_json['name'] = exercise.name
        exercise_json['value'] = exercise.name
        exercise_json['category'] = _(exercise.category.name)
        exercise_json['image'] = image
        exercise_json['image_thumbnail'] = thumbnail

        results.append(exercise_json)
    data = json.dumps(results)

    # Return the results to the server
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)
Пример #54
0
def search(request):
    '''
    Search an exercise, return the result as a JSON list
    '''

    # Perform the search
    q = request.GET.get('term', '')

    languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)
    exercises = (Exercise.objects.filter(name__icontains=q).filter(
        language__in=languages).filter(
            status__in=Exercise.EXERCISE_STATUS_OK).order_by(
                'category__name', 'name').distinct())

    results = []
    for exercise in exercises:
        if exercise.exerciseimage_set.exists():
            image_obj = exercise.exerciseimage_set.filter(is_main=True)[0]
            image = image_obj.image.url
            t = get_thumbnailer(image_obj.image)
            thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url
        else:
            image = None
            thumbnail = None

        exercise_json = {}
        exercise_json['id'] = exercise.id
        exercise_json['name'] = exercise.name
        exercise_json['value'] = exercise.name
        exercise_json['category'] = _(exercise.category.name)
        exercise_json['image'] = image
        exercise_json['image_thumbnail'] = thumbnail

        results.append(exercise_json)
    data = json.dumps(results)

    # Return the results to the client
    return HttpResponse(data, content_type='application/json')
Пример #55
0
from django.core.exceptions import ValidationError
from django.contrib.contenttypes.fields import GenericRelation
from django.utils.encoding import python_2_unicode_compatible

from easy_thumbnails.fields import ThumbnailerImageField
from easy_thumbnails.alias import aliases

from instances.models import InstanceMixin, InstanceManager
from speeches.utils.audio import AudioHelper
from speeches.utils.text import url_to_unicode

from popolo.models import Person
from sluggable.fields import SluggableField
from sluggable.models import Slug as SlugModel

if not aliases.get('speaker-thumb'):
    aliases.set('speaker-thumb', {'size': (96, 96), 'crop': 'smart', 'upscale': True, 'face': True})

if not aliases.get('speaker-rectangle'):
    aliases.set('speaker-rectangle', {'size': (96, 0), 'upscale': True})

logger = logging.getLogger(__name__)

max_date = datetime.date(datetime.MAXYEAR, 12, 31)
max_time = datetime.time(23, 59)
max_datetime = datetime.datetime.combine(max_date, max_time)


class cache(object):
    '''Computes attribute value and caches it in the instance.
    Python Cookbook (Denis Otkidach) http://stackoverflow.com/users/168352/denis-otkidach
Пример #56
0
    def render(self, context):
        # Note that this isn't a global constant because we need to change the
        # value for tests.
        raise_errors = settings.THUMBNAIL_DEBUG
        # Get the source file.
        try:
            source = self.source_var.resolve(context)
        except VariableDoesNotExist:
            if raise_errors:
                raise VariableDoesNotExist(
                    "Variable '%s' does not exist." % self.source_var)
            return self.bail_out(context)
        if not source:
            if raise_errors:
                raise TemplateSyntaxError(
                    "Variable '%s' is an invalid source." % self.source_var)
            return self.bail_out(context)
        # Resolve the thumbnail option values.
        try:
            opts = {}
            for key, value in six.iteritems(self.opts):
                if hasattr(value, 'resolve'):
                    value = value.resolve(context)
                opts[str(key)] = value
        except Exception:
            if raise_errors:
                raise
            return self.bail_out(context)
        # Size variable can be either a tuple/list of two integers or a
        # valid string.
        size = opts['size']
        if isinstance(size, six.string_types):
            m = RE_SIZE.match(size)
            if m:
                opts['size'] = (int(m.group(1)), int(m.group(2)))
            else:
                # Size variable may alternatively be referencing an alias.
                alias = aliases.get(size, target=source)
                if alias:
                    del opts['size']
                    opts = dict(alias, **opts)
                else:
                    if raise_errors:
                        raise TemplateSyntaxError(
                            "%r is not a valid size." % size)
                    return self.bail_out(context)
        # Ensure the quality is an integer.
        if 'quality' in opts:
            try:
                opts['quality'] = int(opts['quality'])
            except (TypeError, ValueError):
                if raise_errors:
                    raise TemplateSyntaxError(
                        "%r is an invalid quality." % opts['quality'])
                return self.bail_out(context)
        # Ensure the subsampling level is an integer.
        if 'subsampling' in opts:
            try:
                opts['subsampling'] = int(opts['subsampling'])
            except (TypeError, ValueError):
                if raise_errors:
                    raise TemplateSyntaxError(
                        "%r is an invalid subsampling level." %
                        opts['subsampling'])
                return self.bail_out(context)

        try:
            thumbnail = get_thumbnailer(source).get_thumbnail(opts)
        except Exception:
            if raise_errors:
                raise
            return self.bail_out(context)
        # Return the thumbnail file url, or put the file on the context.
        if self.context_name is None:
            return escape(thumbnail.url)
        else:
            context[self.context_name] = thumbnail
            return ''
Пример #57
0
 def thumbnail(self):
     for picture in self.pictures:
         thumbnailer = get_thumbnailer(picture.attachment_file)
         return thumbnailer.get_thumbnail(aliases.get('small-square'))
     return None
Пример #58
0
 def test_global(self):
     self.assertEqual(aliases.get('invalid'), None)
     self.assertEqual(aliases.get('small'), {'size': (100, 100)})
     self.assertEqual(aliases.get('avatar'), None)
     self.assertEqual(aliases.get('banner'), None)