'Post, in_memory images files to external python | Django Rest Framework API
Here is the scenario of this post..... A user will post some images to REST API, I have to get those images and post them to an external API to get scores calculated from an AI Modal.
I have found many solutions to post the stored images to an external API, But could not find anything related to in-memory objects, SO I am posting my Solution over here so that it will be easier for someone else next time. If you have any suggestions feel free to comment
import requests
from rest_framework.exceptions import ValidationError
def external_api(img):
api_endpoint = 'YOUR_EXTERNAL_API'
payload = {}
files = [
('img', (img.get("img").name, img.get('img').file, img.get("img").content_type))
]
headers = {}
response = requests.request("POST", api_endpoint, headers=headers, data=payload, files=files)
return response
#Serializer
class ScoreCardSerializer(serializers.ModelSerializer):
score_data = serializers.JSONField(read_only=True, required=False)
class Meta:
model = ScoreCard
exclude = ['card_display']
def create(self, validated_data):
score_image = validated_data.pop('score_card_image')
ai_response = []
for image in score_image:
ai = external_api(image)
if ai.status_code == 200:
ai_response.append(ai.json())
else:
raise ValidationError("Server is overloaded. Please try again in few minutes")
specie = ScoreCard.objects.create(**validated_data)
for image in score_image:
Images.objects.create(score_card_id=specie.id, img=image['img'])
specie.score_data = ai_response
specie.save()
return specie
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
