码迷,mamicode.com
首页 > 其他好文 > 详细

django rest_framework比较完整的自定义实现样例

时间:2017-08-29 11:12:26      阅读:1734      评论:0      收藏:0      [点我收藏+]

标签:sites   div   validate   fat   csrf   更新   get   cal   objects   

里面有自定义的更新策略,

序列化时,考虑nest及显示。

很有参考意义。

然后,前端,可以考虑用angular.js或vue.js实现。

每次以token进行认证。

url.py

router = DefaultRouter()
router.register(rsubserver, api_views.SubserverViewSet, base_name="subserver")
router.register(rdeploypool, api_views.DeployPoolViewSet, base_name="deploypool")
router.register(rversionpool, api_views.VersionPoolViewSet, base_name="versionpool")
router.register(rusers, api_views.UserViewSet, base_name="users")
router.register(rserver, api_views.ServerViewSet, base_name="server")
router.register(rsite, api_views.SiteViewSet, base_name="site")
router.register(rapp, api_views.AppViewSet, base_name="app")

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    deploy_create_user = serializers.HyperlinkedRelatedField(many=True, view_name=api:deploypool-detail, read_only=True)

    class Meta:
        model = User
        fields = (id, username, deploy_create_user,)


class TokenSerializer(serializers.ModelSerializer):
    token = serializers.ReadOnlyField(source=create_user.username)

    class Meta:
        model = User
        fields = (id, username, code, linenos, language, style)


class ServerSerializer(serializers.HyperlinkedModelSerializer):
    ip_subserver = serializers.HyperlinkedRelatedField(many=True, view_name=api:subserver-detail, read_only=True)
    # app_name = serializers.ReadOnlyField(source=‘app_name.name‘)

    class Meta:
        model = Server
        fields = (id, server_env, name, server_sys, ip_subserver)


class SubserverSerializer(serializers.HyperlinkedModelSerializer):
    app_name = serializers.HyperlinkedRelatedField(view_name=api:app-detail, read_only=True)
    # server_ip = serializers.ReadOnlyField(source=‘server_ip.name‘)

    class Meta:
        model = SubServer
        fields = (id, deploy_status, app_name, )


class SiteSerializer(serializers.HyperlinkedModelSerializer):
    app_name = serializers.HyperlinkedRelatedField(many=True, view_name=api:app-detail, read_only=True)

    class Meta:
        model = Site
        fields = (id, name, app_name)


class SiteListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Site
        fields = (id, name)


class DeployPoolSerializer(serializers.ModelSerializer):
    create_user = serializers.ReadOnlyField(source=create_user.username)
    site_name = serializers.ReadOnlyField(source=site_name.name)
    version_name = serializers.ReadOnlyField(source=version_name.name)
    app_name = serializers.ReadOnlyField(source=app_name.name)

    class Meta:
        model = DeployPool
        fields = (id, name, site_name, version_name, app_name,
                  order_no, deploy_status, deploy_progress, create_user, change_date )


class AppSerializer(serializers.HyperlinkedModelSerializer):
    site_app = serializers.HyperlinkedRelatedField(many=True, view_name=api:site-detail, read_only=True)

    class Meta:
        model = SubServer
        fields = (id, name, site_app,)


class VersionPoolSerializer(serializers.ModelSerializer):
    # 注意外键名称显示,nest field显示时的配置
    site_name = serializers.ReadOnlyField(source=site_name.name)
    dep_version = DeployPoolSerializer(many=True, required=False, read_only=True)
    create_user = serializers.ReadOnlyField(source=create_user.username)

    class Meta:
        model = VersionPool
        fields = (id, name, site_name, is_order, version_progress,  dep_version, create_user, add_date)

views.py

@csrf_exempt
def gettoken():
    pass


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (permissions.AllowAny,)
    paginate_by = 10

    def get_queryset(self):
        queryset = self.queryset.filter(username=kevin)
        return queryset


class SiteViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = Site.objects.all()
    serializer_class = SiteSerializer
    permission_classes = (permissions.AllowAny,)
    paginate_by = 10


class SiteListAPI(generics.ListAPIView):
    """
    This ListAPIView automatically provides `list` actions.
    """
    queryset = Site.objects.all()
    serializer_class = SiteListSerializer
    paginate_by = 1000


class AppViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = App.objects.all()
    serializer_class = AppSerializer
    permission_classes = (permissions.AllowAny,)
    paginate_by = 10


class ServerViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = Server.objects.all()
    serializer_class = ServerSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, )
    paginate_by = 10


class SubserverViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    queryset = SubServer.objects.all()
    serializer_class = SubserverSerializer
    permission_classes = (permissions.AllowAny,)
    paginate_by = 10

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class DeployPoolViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    serializer_class = DeployPoolSerializer
    authentication_classes = (TokenAuthentication,)
    paginate_by = 1000

    def get_queryset(self):
        filter_dict = dict()

        if self.request.query_params.get(site_name):
            filter_dict[site_name__name] = self.request.query_params.get(site_name)
        if self.request.query_params.get(order_no):
            filter_dict[order_no] = self.request.query_params.get(order_no)
        if self.request.query_params.get(version_name):
            if self.request.query_params.get(version_name) == "null":
                filter_dict[version_name__isnull] = True
            else:
                filter_dict[version_name__name] = self.request.query_params.get(version_name)
        # 以下过滤发布单的环境及时间(30天)
        # filter_dict[‘deploy_progress‘] = u"待发布"
        filter_dict[deploy_status__in] = ["UAT", "PRD", "SIM", "DRP", "BUILD", "FAT", "DEV"]
        current_date = timezone.now()
        filter_dict[change_date__gt] = current_date - timedelta(days=3000)

        return DeployPool.objects.filter(**filter_dict)

    def update(self, request, *args, **kwargs):
        name = request.data[name]
        order_no = request.data[order_no]
        version_name = request.data[version_name]

        try:
            if version_name:
                version_item = VersionPool.objects.get(name=version_name)
                DeployPool.objects.filter(name=name).update(order_no=order_no, version_name=version_item)
            else:
                DeployPool.objects.filter(name=name).update(order_no=order_no, version_name=None)
            response_data = {
                result: success,
                name: name,
                create_user: request.user.username,
                message: 更新发布单成功!
            }
            return Response(response_data, status=status.HTTP_201_CREATED)
        except:
            response_data = {
                result: failed,
                message: 更新发布单失败!
            }
            return Response(response_data, status=status.HTTP_400_BAD_REQUEST)


class VersionPoolViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    queryset = VersionPool.objects.all()
    serializer_class = VersionPoolSerializer
    authentication_classes = (TokenAuthentication,)
    paginate_by = 100

    def get_queryset(self):
        queryset = self.queryset
        return queryset

    # 如有需要,自定义update和create方法,以实现外键方面的关联
    def create(self, request, *args, **kwargs):
        name = request.data[name]
        site_name = request.data[site_name]
        validated_data = dict()
        validated_data[name] = site_name + "-" + name
        try:
            validated_data[site_name] = Site.objects.get(name=site_name)
        except:
            response_data = {
                result: failed,
                name: site_name + "-" + name,
                create_user: request.user.username,
                message: 项目名不存在!
            }
            return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
        validated_data[create_user] = request.user
        try:
            VersionPool.objects.create(**validated_data)
            response_data = {
                result: success,
                name: site_name + "-" + name,
                create_user: request.user.username,
                message: 创建版本单成功!
            }
            return Response(response_data, status=status.HTTP_201_CREATED)
        except:
            response_data = {
                result: failed,
                name: site_name + "-" + name,
                create_user: request.user.username,
                message: 已存在相同版本单
            }
            return Response(response_data, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, *args, **kwargs):

        if request.data["isOrder"] == "false":
            is_order = False
        else:
            is_order = True

        print request.data, "%%%%%%%%%%%%%%%%%%%%%%%%%"

        VersionPool.objects.filter(id=kwargs["pk"]).update(is_order=is_order)

        try:
            response_data = {
                result: success,
                create_user: request.user.username,
                message: 更新版本单成功!
            }
            return Response(response_data, status=status.HTTP_201_CREATED)
        except:
            response_data = {
                result: failed,
                message: 更新版本单失败!
            }
            return Response(response_data, status=status.HTTP_400_BAD_REQUEST)

 

django rest_framework比较完整的自定义实现样例

标签:sites   div   validate   fat   csrf   更新   get   cal   objects   

原文地址:http://www.cnblogs.com/aguncn/p/7447016.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!