2017-01-16 104 views
1

我想知道我必須做什麼來區分GET和POST在Django Rest Framework的ModelViewSet中,因爲它混合購買,我不知道該怎麼做。在ModelViewset Django Rest Framework中區分GET和POST


基本上我想打一個API,允許上傳兩張圖片和POST調用的響應是取決於上傳的圖片的相似程度的一個數字。爲此,我打算通過POST調用來獲取存儲圖像的路徑,以便能夠在OpenCV中使用另一個腳本來處理它們。然後我把我有的代碼,它允許您上傳兩個圖像。

## Models.py ## 
    class Task(models.Model): 
     task_name = models.CharField(max_length=20) 
     image1 = models.ImageField(upload_to='Images/',default='Images/None/No-img.jpg') 
     image2 = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg') 

     def __str__(self): 
      return "%s" % self.task_name 
    ## Serializers.py ## 

    class TaskSerializer(serializers.ModelSerializer): 

    image1 = serializers.ImageField(max_length=None,use_url=True) 
    image2 = serializers.ImageField(max_length=None, use_url=True) 
    class Meta: 
     model = Task 
     fields = ('id','task_name','image1','image2') 

## Views.py ## 

    class TaskViewSet(viewsets.ModelViewSet): 
     queryset = Task.objects.all() 
     serializer_class = TaskSerializer 

## Urls.py ## 

    router = routers.DefaultRouter() 
    router.register(r'task', views.TaskViewSet) urlpatterns = [ 
    url(r'^',include(router.urls)), 
    url(r'^admin/', include(admin.site.urls)), 
    ] 
+1

你的問題還不清楚,你是什麼意思區分get和post?這是一個觀點集的整個觀點 – Sayse

回答

0

如果我說得對,您需要在創建任務後比較您的圖像。

from rest_framework.decorators import detail_route 
from rest_framework.response import Response 

class TaskViewSet(viewsets.ModelViewSet): 
    queryset = Task.objects.all() 
    serializer_class = TaskSerializer 

    @detail_route(methods=['post']) 
     def perform_task(self, request, pk=None): 
      task = self.get_object() 
      serializer = PasswordSerializer(data=request.data) 
     if serializer.is_valid(): 
      task.save() 
      # here you run your code to set similarity 
      return Response({'similarity': similarity}) 
     else: 
      return Response(serializer.errors, 
          status=status.HTTP_400_BAD_REQUEST) 
相關問題