2024-04-23 11:03:34 +00:00
|
|
|
|
# coding=utf-8
|
|
|
|
|
|
"""
|
|
|
|
|
|
@project: maxkb
|
|
|
|
|
|
@Author:虎
|
|
|
|
|
|
@file: image_serializers.py
|
|
|
|
|
|
@date:2024/4/22 16:36
|
|
|
|
|
|
@desc:
|
|
|
|
|
|
"""
|
|
|
|
|
|
import uuid
|
|
|
|
|
|
|
|
|
|
|
|
from django.db.models import QuerySet
|
|
|
|
|
|
from django.http import HttpResponse
|
|
|
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
|
|
|
|
from common.exception.app_exception import NotFound404
|
2024-08-07 06:28:08 +00:00
|
|
|
|
from common.field.common import UploadedImageField
|
2024-04-23 11:03:34 +00:00
|
|
|
|
from common.util.field_message import ErrMessage
|
|
|
|
|
|
from dataset.models import Image
|
2025-01-13 08:38:28 +00:00
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
2024-04-23 11:03:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ImageSerializer(serializers.Serializer):
|
2025-01-13 08:38:28 +00:00
|
|
|
|
image = UploadedImageField(required=True, error_messages=ErrMessage.image(_('image')))
|
2024-04-23 11:03:34 +00:00
|
|
|
|
|
|
|
|
|
|
def upload(self, with_valid=True):
|
|
|
|
|
|
if with_valid:
|
|
|
|
|
|
self.is_valid(raise_exception=True)
|
|
|
|
|
|
image_id = uuid.uuid1()
|
|
|
|
|
|
image = Image(id=image_id, image=self.data.get('image').read(), image_name=self.data.get('image').name)
|
|
|
|
|
|
image.save()
|
|
|
|
|
|
return f'/api/image/{image_id}'
|
|
|
|
|
|
|
|
|
|
|
|
class Operate(serializers.Serializer):
|
|
|
|
|
|
id = serializers.UUIDField(required=True)
|
|
|
|
|
|
|
|
|
|
|
|
def get(self, with_valid=True):
|
|
|
|
|
|
if with_valid:
|
|
|
|
|
|
self.is_valid(raise_exception=True)
|
|
|
|
|
|
image_id = self.data.get('id')
|
|
|
|
|
|
image = QuerySet(Image).filter(id=image_id).first()
|
|
|
|
|
|
if image is None:
|
2025-01-13 08:38:28 +00:00
|
|
|
|
raise NotFound404(404, _('Image not found'))
|
2024-07-23 11:11:49 +00:00
|
|
|
|
if image.image_name.endswith('.svg'):
|
|
|
|
|
|
return HttpResponse(image.image, status=200, headers={'Content-Type': 'image/svg+xml'})
|
2024-10-29 07:17:50 +00:00
|
|
|
|
# gif
|
|
|
|
|
|
elif image.image_name.endswith('.gif'):
|
|
|
|
|
|
return HttpResponse(image.image, status=200, headers={'Content-Type': 'image/gif'})
|
2024-04-23 11:03:34 +00:00
|
|
|
|
return HttpResponse(image.image, status=200, headers={'Content-Type': 'image/png'})
|