Exemplo n.º 1
0
def serve_protected_thumbnail(request, path):
    """
    Serve protected thumbnails to authenticated users.
    If the user doesn't have read permissions, redirect to a static image.
    """
    source_path = thumbnail_to_original_filename(path)
    if not source_path:
        raise Http404('File not found')
    try:
        file_obj = File.objects.get(file=source_path, is_public=False)
    except File.DoesNotExist:
        raise Http404('File not found')
    if not file_obj.has_read_permission(request):
        if settings.DEBUG:
            raise PermissionDenied
        else:
            raise Http404('File not found')
    try:
        thumbnail = ThumbnailFile(name=path,
                                  storage=file_obj.file.thumbnail_storage)
        thumbnail_temp_file = File(file=thumbnail,
                                   mime_type=file_obj.mime_type)
        return thumbnail_server.serve(request,
                                      thumbnail_temp_file,
                                      save_as=False)
    except Exception:
        raise Http404('File not found')
def load_random_file():
    """Load random file."""
    # We should load ``ThumbnailFile`` here, since otherwise we might get
    # ``AppRegistryNotReady`` exception.
    from easy_thumbnails.files import ThumbnailFile

    media_root = os.path.abspath(django_settings.MEDIA_ROOT)
    static_root = os.path.abspath(django_settings.STATIC_ROOT)

    random_image = get_random_image()

    if PY3:
        random_file = codecs.open(random_image, mode='rb')
    else:
        random_file = codecs.open(random_image)

    source = ThumbnailFile(random_file.name, random_file)
    source.name = source.file.name \
        .replace(media_root, '') \
        .replace(static_root, '')[1:]

    return source