zoukankan      html  css  js  c++  java
  • user/views.py

    from django.http import HttpResponse

    from django_filters.rest_framework import DjangoFilterBackend

    from rest_framework import viewsets

    from rest_framework.authentication import BasicAuthentication, SessionAuthentication

    from rest_framework.decorators import action

    from rest_framework.filters import OrderingFilter

    from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated, IsAuthenticatedOrReadOnly

    from rest_framework.response import Response

    from rest_framework.throttling import UserRateThrottle

    from rest_framework.pagination import PageNumberPagination

    from rest_framework.views import APIView

    from rest_framework.permissions import BasePermission, SAFE_METHODS

    from user.models import User

    from user.serializers import UserSerializer, UserUnActiveSerializer

    def index(request):

      # 需要认证才能访问的视图

      return HttpResponse('hello')

    # 分页(局部):自定义分页器 局部

    class PageNum(PageNumberPagination):

      # 查询字符串中代表每页返回数据数量的参数名, 默认值: None

      page_size_query_param = 'page_size'

      # 查询字符串中代表页码的参数名, 有默认值: page

      # page_query_param = 'page'

      # 一页中最多的结果条数 max_page_size = 2

    # 自定义权限(局部)

    class MyPermission(BasePermission):

      # has_permission 是用户对这个视图有没有 GET POST PUT PATCH DELETE 权限的分别判断

      def has_permission(self, request, view):

        print('has_perm')

        # print(view.kwargs.get("pk"), request.user.id)

        """判断用户对模型有没有访问权"""

        # 任何用户对使用此权限类的视图都有访问权限

        if request.user.is_superuser:

          # 管理员对用户模型有访问权

          return True

        elif view.kwargs.get('pk') == str(request.user.id):

          # 携带的id和用户的id相同时有访问权

          return True

        return False

      # has_object_permission 是用户过了 has_permission 判断有权限以后,再判断这个用户有 没有对一个具体的对象有没有操作权限

      # 这样设置以后,即使是django admin管理员也只能查询自己user标的信息,不能查询其他用户的 单条信息

      def has_object_permission(self, request, view, obj):

        print('has_object_perm')

        """获取单个数据时,判断用户对某个数据对象是否有访问权限"""

        if request.user.id == obj.id:

          return True

        return False

    class UserViewSet(viewsets.ModelViewSet):

      """ 完成产品的增删改查 """

      queryset = User.objects.all()

      serializer_class = UserSerializer               # 优先使用 get_serializer_class 返回的序列化 器

      # # 1.认证:自定义认证类, 自定义会覆盖全局配置

      # authentication_classes = (BasicAuthentication, SessionAuthentication)

      # # 2.权限:自定义权限类

      # permission_classes = (MyPermission,)

      # 3.分页:自定义分页器 覆盖全局配置

      pagination_class = PageNum

      # 4.限流:自定义限流类

      throttle_classes = [UserRateThrottle]

      # 5.过滤:指定过滤方法类, 排序方法类, 一个或多个

      filter_backends = (DjangoFilterBackend, OrderingFilter)                # 同时支持过滤和排序

      # 5.1指定排序字段, 不设置, 排序功能不起效

      ordering_fields = ('date_joined', 'id')                         # ?ordering=-id

      # 5.2指定过滤字段, 不设置, 过滤功能不起效

      filter_fields = ('username', 'phone', 'is_active')               # ? username=tom&phone=&is_active=true

      # 根据不同的请求, 获得不同的序列化器

      def get_serializer_class(self):

        if self.action == 'unactived':

          return UserUnActiveSerializer

        else:

          return UserSerializer

      @action(methods=['get'], detail=False)

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

        # 获取查询集, 过滤出未激活的用户

        qs = self.queryset.filter(is_active=False)

        # 使用序列化器, 序列化查询集, 并且是

        ser = self.get_serializer(qs, many=True)

        return Response(ser.data)

      @action(methods=['get'], detail=False)

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

        # 获取查询集, 过滤出未激活的用户

        qs = self.queryset.filter(is_active=True)

        # 使用序列化器, 序列化查询集, 并且是

        ser = self.get_serializer(qs, many=True)

        return Response(ser.data)

  • 相关阅读:
    关于celery踩坑
    关于git的分批提交pull requests流程
    SymGAN—Exploiting Images for Video Recognition: Heterogeneous Feature Augmentation via Symmetric Adversarial Learning学习笔记
    AFN—Larger Norm More Transferable: An Adaptive Feature Norm Approach for Unsupervised Domain Adaptation学习笔记
    Learning to Transfer Examples for Partial Domain Adaptation学习笔记
    Partial Adversarial Domain Adaptation学习笔记
    Partial Transfer Learning with Selective Adversarial Networks学习笔记
    Importance Weighted Adversarial Nets for Partial Domain Adaptation学习笔记
    Exploiting Images for Video Recognition with Hierarchical Generative Adversarial Networks学习笔记
    improved open set domain adaptation with backpropagation 学习笔记
  • 原文地址:https://www.cnblogs.com/aa1bb2/p/13887835.html
Copyright © 2011-2022 走看看