python - run some function after taking input from api django
问题描述
I have one webapp where user post image and then opencv calculate its details like width, height and show back. I got this from webapp but when I trying to get the same with API I can't figure out how should I do this here my code:
Serializers.py
from rest_framework import serializers
from results.models import Result
import cv2
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Result
fields = ('title','pub_date','medium','compound','detail','outputval','image','uploader')
models.py:
class Result(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateField()
medium = models.CharField(max_length=200)
compound = models.CharField(max_length=200)
detail = models.TextField()
outputval = models.TextField(default='rsult not calculated', null=True, blank=True)
image = models.ImageField(upload_to='images/')
uploader = models.ForeignKey(User, on_delete=models.CASCADE) # will be changed to not delete in update
views.py:
from rest_framework import viewsets
from .serializers import ImageSerializer
from results.models import Result
class ImageViewSet(viewsets.ModelViewSet):
queryset = Result.objects.all()
serializer_class = ImageSerializer
opencv function:
def opencv(self,img_path):
image = cv2.imread(img_path)
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]
values = (" the height is %s , width is %s and number of channels is %s" % (height, width, channels))
return values
what i want to do take image as user input and show the output in outputval fields.
解决方案
序列化程序.py
from results.models import Result
import cv2
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Result
fields = '__all__'
def create(self, validated_data):
instance = super().create(validated_data)
instance.outputval = opencv(instance.image.path)
instance.save()
return instance
我想是这样的。这样,当 ModelViewSet 上的 create 函数返回序列化程序的数据时,您的outputval 就会被填充。
推荐阅读
- typescript - 从类型中删除未定义
- javascript - 如何在 JavaScript 中将数组 api 响应转换为 json
- amazon-web-services - 有没有办法使用 lambda 将数据从 S3 导出到 Amazon Aurora 无服务器?
- .net - 在 WPF 应用程序中拥有多个 D3DImage(比如 5 个)元素是个好主意吗?
- python - 当 force_login() 在详细视图上时,Django Rest Framework 在单元测试中给出 302?
- validation - XBRL 验证工具
- flutter - 如何在颤动中将行和列的大小设置为其父小部件?
- c# - 每次迭代或循环浏览文档列表时,如何创建新的 PDF 文件?
- c - 与位置无关的可执行文件:什么是“主要可执行二进制文件”?
- jquery - 在 php 字符串中使用替换函数