from coverage.annotate import os from django.http import HttpResponse from django.urls import path from drf_yasg.utils import swagger_auto_schema from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from core.settings import MEDIA_ROOT from files.models import File @swagger_auto_schema(method='GET', auto_schema=None) @api_view(['GET']) def media_urls(request, hash_path): try: file = File.objects.get(file=hash_path) return HttpResponse(status=status.HTTP_200_OK, content_type=file.mime_type, headers={ 'X-Accel-Redirect': f'/redirect_media/{hash_path}', 'Access-Control-Allow-Origin': '*', }) # TODO Expires and Cache-Control except File.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) @swagger_auto_schema(method='GET', auto_schema=None) @api_view(['GET']) def thumbnail_urls(request, size, hash_path): if size not in [32, 64, 256]: return Response(status=status.HTTP_404_NOT_FOUND) try: file = File.objects.get(file=hash_path) if not os.path.exists(MEDIA_ROOT + f'/thumbnails/{size}/{hash_path}'): from PIL import Image iamge = Image.open(file.file) iamge.thumbnail((size, size)) iamge.save(MEDIA_ROOT + f'/media/thumbnails/{size}/{hash_path}', quality=90) return HttpResponse(status=status.HTTP_200_OK, content_type=file.mime_type, headers={ 'X-Accel-Redirect': f'/redirect_thumbnail/{size}/{hash_path}', 'Access-Control-Allow-Origin': '*', }) # TODO Expires and Cache-Control except File.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) urlpatterns = [ path('/', thumbnail_urls), path('', media_urls), ]