Handle received image

This commit is contained in:
Gabriel Augendre 2021-02-15 19:29:07 +01:00
parent 4e170074b7
commit 4ef51abc8b
1 changed files with 11 additions and 1 deletions

View File

@ -1,8 +1,10 @@
import base64
import json
from smtplib import SMTPException
from anymail.exceptions import AnymailRequestsAPIError
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
@ -11,7 +13,7 @@ from django.views import generic
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from django.views.decorators.http import require_http_methods
from pictures.models import Contact, Message
from pictures.models import Contact, Media, Message
STATUS_OK = "ok"
STATUS_ERROR = "error"
@ -76,6 +78,14 @@ def create_message(request):
contact, _ = Contact.objects.get_or_create(phone_number=phone_number)
content = data.get("content", "")
message = Message.objects.create(sender=contact, content=content)
base64_data = data.get("image_base64")
if base64_data:
mime_type, image_string = base64_data.split(";base64,")
ext = mime_type.split("/")[-1]
image_file = ContentFile(
base64.b64decode(image_string), name=f"{message.pk}.{ext}"
)
Media.objects.create(message=message, file=image_file)
except Exception as e:
return _error_response(str(e))
return JsonResponse({"status": STATUS_OK, "data": {"id": message.pk}}, status=201)