从api django输入后运行一些功能

时间:2019-02-25 20:37:55

标签: python django opencv django-rest-framework

我有一个webapp,用户在其中发布图像,然后opencv计算其详细信息,例如宽度,高度并向后显示。我是从webapp那里得到的,但是当我尝试通过API获得相同的信息时,我不知道该怎么做 这是我的代码:

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函数:

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

我想将图像作为用户输入并在outputval字段中显示输出。

1 个答案:

答案 0 :(得分:1)

serializer.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