56 lines
1.7 KiB
Python
56 lines
1.7 KiB
Python
import imghdr
|
|
from wsgiref.util import FileWrapper
|
|
|
|
import structlog
|
|
from django.conf import settings
|
|
from django.contrib.auth.decorators import login_required
|
|
from django.http import HttpResponse, StreamingHttpResponse
|
|
from django.shortcuts import get_object_or_404
|
|
from wagtail.images.exceptions import InvalidFilterSpecError
|
|
from wagtail.images.models import SourceImageIOError
|
|
|
|
from vbv_lernwelt.media_files.models import UserImage
|
|
|
|
logger = structlog.get_logger(__name__)
|
|
|
|
|
|
@login_required
|
|
def user_image(request, image_id):
|
|
image = get_object_or_404(UserImage, id=image_id)
|
|
|
|
filter_spec = request.GET.get("filter", "original")
|
|
|
|
try:
|
|
rendition = image.get_rendition(filter_spec)
|
|
|
|
rendition.file.open("rb")
|
|
image_format = imghdr.what(rendition.file)
|
|
|
|
return StreamingHttpResponse(
|
|
FileWrapper(rendition.file),
|
|
content_type=(
|
|
f"image/{image_format}" if image_format else "binary/octet-stream"
|
|
),
|
|
)
|
|
except SourceImageIOError:
|
|
return HttpResponse(
|
|
"Source image file not found", content_type="text/plain", status=410
|
|
)
|
|
except InvalidFilterSpecError:
|
|
return HttpResponse(
|
|
"Invalid filter spec: " + filter_spec,
|
|
content_type="text/plain",
|
|
status=400,
|
|
)
|
|
except Exception:
|
|
if settings.APP_ENVIRONMENT.startswith("local"):
|
|
# do not spam the console
|
|
logger.warning("Error while serving image")
|
|
else:
|
|
logger.exception(
|
|
"Error while serving image", exc_info=True, label="s3_mediafiles"
|
|
)
|
|
return HttpResponse(
|
|
"Error while serving image", content_type="text/plain", status=400
|
|
)
|