serve images via X-Sendfile
This commit is contained in:
parent
27589a09bd
commit
153d79f126
2 changed files with 16 additions and 11 deletions
61
core/files/media_v1.py
Normal file
61
core/files/media_v1.py
Normal file
|
@ -0,0 +1,61 @@
|
|||
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, permission_classes, authentication_classes
|
||||
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'])
|
||||
@permission_classes([])
|
||||
@authentication_classes([])
|
||||
def media_urls(request, hash):
|
||||
try:
|
||||
file = File.objects.get(hash=hash)
|
||||
hash_path = file.file
|
||||
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'])
|
||||
@permission_classes([])
|
||||
@authentication_classes([])
|
||||
def thumbnail_urls(request, hash):
|
||||
size = 200
|
||||
try:
|
||||
file = File.objects.get(hash=hash)
|
||||
hash_path = file.file
|
||||
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('thumbs/<path:hash>', thumbnail_urls),
|
||||
path('images/<path:hash>', media_urls),
|
||||
]
|
Loading…
Add table
Add a link
Reference in a new issue