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

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

很有参考意义。

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

每次以token进行认证。

url.py

router = DefaultRouter()
router.register(r'subserver', api_views.SubserverViewSet, base_name="subserver")
router.register(r'deploypool', api_views.DeployPoolViewSet, base_name="deploypool")
router.register(r'versionpool', api_views.VersionPoolViewSet, base_name="versionpool")
router.register(r'users', api_views.UserViewSet, base_name="users")
router.register(r'server', api_views.ServerViewSet, base_name="server")
router.register(r'site', api_views.SiteViewSet, base_name="site")
router.register(r'app', 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比较完整的自定义实现样例的更多相关文章

  1. 【转】k8s集群自定义clusterRole样例

    对pod资源可以删除,进入终端执行命令,其他资源只读权限 apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: an ...

  2. 通过Canvas及File API缩放并上传图片完整演示样例

    创建一个只管的用户界面,并同意你控制图片的大小.上传到server端的数据,并不须要处理enctype为 multi-part/form-data 的情况.只一个简单的POST表单处理程序就能够了. ...

  3. Android之——多线程下载演示样例

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/46883927 一.概述 说到Android中的文件下载.Android API中明 ...

  4. python之Django rest_framework总结

    一.rest api    a.api就是接口         如: - http://www.oldboyedu.com/get_user/                - http://www. ...

  5. Django rest_framework 实用技巧

    前言: 最近工作中需要用到Django rest_framework框架做API, 边学边写,记录了一些实际工作中需要用到的功能,不是很全也不系统,以后需要什么功能可以在这查询. 后续还会更新其它的用 ...

  6. 七、django rest_framework源码之视图

    1 绪言 当大家看大这篇博文的时候,应该对Django rest_framework中的CBV有所了解了,大致来说就是通过定义类来继承APIView类,并在类中定义get.post.put.delet ...

  7. 四、django rest_framework源码之频率控制剖析

    1 绪言 权限判定之后的下一个环节是访问频率控制,本篇我们分析访问频率控制部分源码. 2 源码分析 访问频率控制在dispatch方法中的initial方法调用check_throttles方法开始. ...

  8. 二、django rest_framework源码之认证流程剖析

    1 绪言 上一篇中讲了django rest_framework总体流程,整个流程中最关键的一步就是执行dispatch方法.在dispatch方法中,在调用了一个initial方法,所有的认证.权限 ...

  9. CentOS7 + Python3 + Django(rest_framework) + MySQL + nginx + uwsgi 部署 API 开发环境, 记坑篇

    CentOS7 + Python3 + Django(rest_framework) + MySQL + nginx + uwsgi 部署 API 开发环境 CentOS7 + Python3 + D ...

随机推荐

  1. EXT 翻页后查询 页数不重置

    测试查询条件时,当表格翻页后,输入查询条件,页数不刷新,还是之前的页数,导致列表不显示数据.只要在查询时,将表格的currentPage 设为1 即可. store.currentPage = 1; ...

  2. Drivers Dissatisfaction 最小生成树+LCA

    题意:给一张n个点m条边的连通图,每条边(ai,bi)有一个权值wi和费用ci, 表示这条边每降低1的权值需要ci的花费.现在一共有S费用可以用来降低某些边的权值 (可以降到负数),求图中的一棵权值和 ...

  3. wordpress初始化安装

    数据名,用户名,密码的选择: 从主机购买商的控制面板里面查询: 然后填入到WordPress数据库初始化页面..

  4. HTML5增强的表单

    form元素a.用来定义一个表单,是建立表单的基础元素(就类似定义表格的table)b.表单的其他元素包含在form元素中,其主要子元素有:input/button/select......form元 ...

  5. 使用git拉取github上的项目

    一. 安装Git 去Git官网,下载安装包,一路点next,默认安装. 安装之后,在空白处右键,菜单显示有 Git GUI Here 和 Git Bash Here ,表示Git安装成功. 二. 配置 ...

  6. Linux高级编程--03.make和makfile

    Makefile语法基础 在Linux下,自动化编译工具是通过make命令来完成的(一些工具厂商也提供了它们自己的make命令,如gmake等),make命令的基本格式如下: make [-f mak ...

  7. 用trigger触发datepicker

    jQuery UI的datepicker没有icon图片,工作需要,自己写了一个,原理是用div包裹住datepicker的input和一个button,隐藏掉input,而button被点击后也可以 ...

  8. Spring REST 异常处理

    在上一篇中写到了Spring MVC的异常处理,SpringMVC捕获到异常之后会转到相应的错误页面,但是我们REST API ,一般只返回结果和状态码,比如发生异常,只向客户端返回一个500的状态码 ...

  9. Windows下搭建网络代理

    场景:有些场景下会出现局域网内的某些网段可能由于安全限制,不能访问外网,此时可以通过安装一些工具来实现借助局域网内某些能够上外网的电脑来实现网络代理的功能.以下工具均是使用于Window环境. 服务端 ...

  10. Tomcat处理一个http请求的过程

    假设来自客户的请求为: http://localhost:8080/wsota/wsota_index.jsp 1) 请求被发送到本机端口8080,被在那里侦听的Coyote HTTP/1.1 Con ...