combo/combo/apps/assets/api_views.py

63 lines
2.3 KiB
Python

# combo - content management system
# Copyright (C) 2019 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base64
from io import BytesIO
from django.core.files import File
from rest_framework import permissions, serializers, status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from .models import Asset
class FileSerializer(serializers.Serializer):
content = serializers.CharField(required=True, allow_blank=False)
content_type = serializers.CharField(required=False, allow_null=True)
filename = serializers.CharField(required=False, allow_null=True)
def validate_content(self, value):
try:
return base64.decodebytes(value.encode('ascii'))
except Exception as e:
raise serializers.ValidationError('content must be base64 (%r)' % e)
class AssetSerializer(serializers.Serializer):
asset = FileSerializer(required=True)
class Set(GenericAPIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = AssetSerializer
def post(self, request, key, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
response = {'err': 1, 'err_desc': serializer.errors}
return Response(response, status.HTTP_400_BAD_REQUEST)
data = serializer.validated_data
asset, dummy = Asset.objects.get_or_create(key=key)
asset.asset = File(BytesIO(data['asset']['content']), name=data['asset'].get('filename'))
asset.save()
response = {'err': 0, 'url': request.build_absolute_uri(f'/assets/{key}')}
return Response(response)
view_set = Set.as_view()