You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.8 KiB
Python

import base64
import os
import tempfile
from datetime import datetime
from django.core.exceptions import BadRequest
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from common.utils.owncloud_utls import Owncloud
from containers.models import ContainerPhotos, Container
class Damages(APIView):
def post(self, request, depot_id):
photo = request.data.get("photo")
extension = request.data.get("photo_extension")
with tempfile.NamedTemporaryFile(suffix=f'.{extension}', delete=False) as temp_file:
try:
temp_file.write(base64.b64decode(photo.encode("utf-8")))
temp_file.flush()
temp_file.close() # Close the file before uploading
own_filename = Owncloud.upload_damage_photo(temp_file.name, depot_id)
container_photo = ContainerPhotos()
container_photo.container = Container.objects.get(pk=depot_id)
container_photo.photo = own_filename
container_photo.uploaded_on = datetime.now()
container_photo.uploaded_by = request.user
container_photo.save()
return Response(status=status.HTTP_201_CREATED)
except Exception as ex:
return Response(
{"error": "Failed to process photo"},
status=status.HTTP_400_BAD_REQUEST
)
finally:
if temp_file:
try:
os.unlink(temp_file.name)
except OSError:
pass # Ignore deletion errors
def get(self, request, depot_id):
return Owncloud.get_damages(depot_id)