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

简介: 里面有自定义的更新策略, 序列化时,考虑nest及显示。 很有参考意义。 然后,前端,可以考虑用angular.js或vue.js实现。 每次以token进行认证。 url.py router = DefaultRouter() router.

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

序列化时,考虑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)

 

目录
相关文章
|
前端开发 API 数据格式
Django的restframework接口框架自定义返回数据格式
在前后端分离是大趋势的背景下,前端获取数据都是通过调用后台的接口来获取数据微服务的应用越来越多。Django是Python进行web应用开发常用的web框架,用Django框架进行web应用框架减少了很多工作,通常用很少量的代码就可以实现数据的增、删、改、查的业务应用,同样用Django的restframework的框架对外发布接口也是非常的简单方便,几行代码就可以将数据对象通过接口的方式提供服务。因为在实际开发过程中接口的返回数据有一定的格式,本文介绍通过自定义Response返回对象来自定义接口返回数据格式。
197 1
|
2月前
|
数据库 Python
django中数据库外键可以自定义名称吗
django中数据库外键可以自定义名称吗
|
3月前
|
安全 数据库 数据安全/隐私保护
|
3月前
|
SQL Shell API
python Django教程 之 模型(数据库)、自定义Field、数据表更改、QuerySet API
python Django教程 之 模型(数据库)、自定义Field、数据表更改、QuerySet API
|
3月前
|
中间件 API 网络架构
Django后端架构开发:从匿名用户API节流到REST自定义认证
Django后端架构开发:从匿名用户API节流到REST自定义认证
43 0
|
5月前
|
数据安全/隐私保护 Python
必知的技术知识:django自定义分页器
必知的技术知识:django自定义分页器
|
6月前
|
运维 监控 Serverless
Serverless 应用引擎产品使用之阿里函数计算中在自定义环境下用debian10运行django,用官方层的python3.9,配置好环境变量后发现自定义层的django找不到了如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
|
6月前
|
JSON 前端开发 网络架构
Django的web框架Django Rest_Framework精讲(四)
Django的web框架Django Rest_Framework精讲(四)
|
6月前
|
前端开发 数据库 网络架构
Django的web框架Django Rest_Framework精讲(三)
Django的web框架Django Rest_Framework精讲(三)
|
6月前
|
前端开发 数据库 数据安全/隐私保护
Django的web框架Django Rest_Framework精讲(二)
Django的web框架Django Rest_Framework精讲(二)