gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:32:14 24 4
gpt4 key购买 nike

我有一个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字段中显示输出。

最佳答案

序列化器

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。

关于python - 从api django输入后运行一些功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54874289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com