Django Rest Framework创建REST API仅用于执行 [英] Django Rest Framework Create REST API only for executions

查看:62
本文介绍了Django Rest Framework创建REST API仅用于执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个django项目,在该项目中,我需要为某些执行构建一个rest API,我对模型没有太大的担心,因为我只需要基于用户的输入/调用执行执行。 / p>

这是我的情况:


  1. 主要是部署(我项目中的一个应用程序)


  2. 在获取请求时,用户将获得所有
    部署(对象)的列表。


  3. 用户将发送POST请求到 / deployments 以及完整的
    对象,例如:

      {
    deployment_name: dep4,
    credentials: cre4,
    project_name: pro4 ,
    project_id: 004,
    cluster_name: clus4,
    zone_region: zon4,
    services: Single,
    configuration: conf4,
    routing: route4}

    然后,我需要使用此数据,在此数据的基础上验证并执行一些执行。例如,我将使用第三方API借助此信息在云平台上进行部署。


我真的对DRF的文档感到困惑,尤其是关于序列化程序。


更新:目前,我正在尝试POST:
来自 apiview.py




  class DeploymentsList(APIView):
queryset = DeploymentOnUserModel.objects.all()

def post(自身,请求):
print(request.data)
DeploymentOnUserModel。 objects.create(
部署名称= request.data ['deployment_name'],
凭据= request.data ['credentials'],
project_name = request.data ['project_name'],
project_id = request.data ['project_id'],
cluster_name = request.data ['cluster_name'],
zone_region = request.data ['zone_region'],
服务= request.data ['services'],
configuration = request.data ['configuration'],
routing = request.data ['routing'],

返回Response(request.data)




所以,如何验证传入的数据/请求?


这是我的部署模型:

 类DeploymentOnUserModel(models.Model):
部署名称=模型.CharField(max_length = 256,)
凭据=模型.TextField(空白= False)
project_name =模型.CharField(max_length = 150,blank = False)
project_id = models.CharField(max_length = 150,blank = True)
cluster_name = models.CharField(max_length = 256,blank = False)
zone_region = models.CharField(max_length = 150,blank = False)
服务= models.CharField(max_length = 150,choices = services)
配置= models.TextField()
路由= models.TextField()

def s ave(self,** kwargs):
,如果不是self.id和self.services =='Multiple'而不是self.routing和self.configuration:
提高ValidationError(为多个服务部署提供路由。)
super()。save(** kwargs)



< blockquote>

来自urls.py:




  app_name ='deployments '

urlpatterns = [
path('deployments /',apiview.DeploymentsList.as_view(),name ='deployment_list'),
path('deployments /< int :pk>',apiview.DeploymentDetail.as_view(),name ='deployment_detail')

]

我应该使用哪种方法和DRF中的东西来实现我的API。

解决方案

实施DRF ModelSerializer ModelViewSet ,以便您可以轻松地重用已有的Django模型。



您的序列化器可能是这样的(例如在 serializers.py )中:

 从rest_framework导入序列化器$ b $ .models中的b 
导入DeploymentOnUser


类DeploymentOnUserModelSerializer(serializers.ModelSerializer):
类元:
模型= DeploymentOnUser
字段= (deployment_name,凭据)

您应该在此处添加自己的验证,就像使用Django一样



视图集可能是这样的(例如在 views.py 中):

  from rest_framework导入视图集
from rest_framework.response import响应

from .models import DeploymentOnUserModel
from .serializers import DeploymentOnUserModelSerializer


class DeploymentOnUserViewSet(viewsets.ModelViewSet):
queryset = DeploymentOnUserModel.objects.all()
serializer_class = DeploymentOnUserModelSerializer

def create(self,reques t,* args,** kwargs):
将其覆盖以进行其他操作
serializer = self.serializer_class(data = request.data)
serializer.is_valid(raise_exception = True)
serializer.save()
返回Response(serializer.data)

根据您的情况,您甚至可能需要覆盖 create -这只是说明了如何实现。



ModelViewSet ModelSerializer 删除了许多样板代码。但是,如果您以前从未使用过DRF,则先阅读教程



别忘了也在 urls.py 中注册视图集:

 从django.conf.urls导入URL,包括

从rest_framework导入路由器
$ b.b从.views导入DeploymentOnUserViewSet


router = routers.DefaultRouter()
router.register('deployments',DeploymentOnUserViewSet)

urlpatterns = [
#其他模式也在这里
url('',include(router.urls)),
]

然后您可以通过执行以下操作来测试您的API在 / deployments / 上进行POST调用。



对于单元测试,我主要使用以下模式:

  from rest_framework.test import APIRequestFactory 

#在根
request = APIRequestFactory上创建一个POST请求().post('/')
响应= DeploymentOnUserViewSet.as_view({'post':'create'})(请求)
断言response.status_code == 200


I'm working on a django project in which I need to build a rest API for some executions, I don't have much concerns about models as I only need to perform executions on the base of user's inputs/calls.

Here's my scenario:

  1. The Major thing is the Deployment ( An App in my project )

  2. On a get request user will get a list of all it's deployments(objects).

  3. A user will send a POST request to /deployments along with the complete object as:

    {
    "deployment_name": "dep4",
    "credentials": "cre4",
    "project_name": "pro4",
    "project_id": "004",
    "cluster_name": "clus4",
    "zone_region": "zon4",
    "services": "Single",
    "configuration": "conf4",
    "routing": "route4" }
    

    then I need to use this data, validate and perform some execution on the base of this data. For example, I will make deployments on a cloud platform with the help of this information by using third-party APIs.

I'm really confused by the documentation of DRF, especially about serializers.

Update: Currently, How I'm trying to do the POST: From apiview.py

class DeploymentsList(APIView):
    queryset = DeploymentOnUserModel.objects.all()

    def post(self, request):
        print(request.data)
        DeploymentOnUserModel.objects.create(
            deployment_name=request.data['deployment_name'],
            credentials=request.data['credentials'],
            project_name=request.data['project_name'],
            project_id=request.data['project_id'],
            cluster_name=request.data['cluster_name'],
            zone_region=request.data['zone_region'],
            services=request.data['services'],
            configuration=request.data['configuration'],
            routing=request.data['routing'],
        )
        return Response(request.data)

So, how can I validate the incoming data/request?

Here's my Deployment Model:

class DeploymentOnUserModel(models.Model):
    deployment_name = models.CharField(max_length=256, )
    credentials = models.TextField(blank=False)
    project_name = models.CharField(max_length=150, blank=False)
    project_id = models.CharField(max_length=150, blank=True)
    cluster_name = models.CharField(max_length=256, blank=False)
    zone_region = models.CharField(max_length=150, blank=False)
    services = models.CharField(max_length=150, choices=services)
    configuration = models.TextField()
    routing = models.TextField()

    def save(self, **kwargs):
        if not self.id and self.services == 'Multiple' and not self.routing and not self.configuration:
            raise ValidationError("You must have to provide routing for multiple services deployment.")
        super().save(**kwargs)

From urls.py:

app_name = 'deployments'

urlpatterns = [
    path('deployments/', apiview.DeploymentsList.as_view(), name='deployment_list'),
    path('deployments/<int:pk>', apiview.DeploymentDetail.as_view(), name='deployment_detail')

]

Which approach and things from DRF I should use to implement my API.

解决方案

You will probably want to implement DRFs ModelSerializer and ModelViewSet such that you can easily reuse the Django model you already have.

Your serializer could be like this (e.g. in serializers.py):

from rest_framework import serializers

from .models import DeploymentOnUser


class DeploymentOnUserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeploymentOnUser
        fields = (deployment_name, credentials, )

You should add your own validation here, much like you would do with Django forms.

The viewset could be like this (e.g. in views.py):

from rest_framework import viewsets
from rest_framework.response import Response

from .models import DeploymentOnUserModel
from .serializers import DeploymentOnUserModelSerializer 


class DeploymentOnUserViewSet(viewsets.ModelViewSet):
    queryset = DeploymentOnUserModel.objects.all()
    serializer_class = DeploymentOnUserModelSerializer 

    def create(self, request, *args, **kwargs):
        """overwrite this for extra actions"""
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

Depending on your situation, you might even need to overwrite create -- this just shows how you could do it.

The ModelViewSet and ModelSerializer remove much of the boilerplate code. However, if you haven't used DRF before, it doesn't hurt to first go through the tutorial

Don't forget to also register the viewset in urls.py:

from django.conf.urls import url, include

from rest_framework import routers

from .views import DeploymentOnUserViewSet


router = routers.DefaultRouter()
router.register('deployments', DeploymentOnUserViewSet)

urlpatterns = [
    # other patterns also go here
    url('', include(router.urls)),
]

You could then test your API by doing e.g. a POST call on /deployments/.

For unit testing, I mostly use this pattern:

from rest_framework.test import APIRequestFactory

# Create a POST request, at the root
request = APIRequestFactory().post('/')
response = DeploymentOnUserViewSet.as_view({'post': 'create'})(request)
assert response.status_code == 200

这篇关于Django Rest Framework创建REST API仅用于执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆