django基础之初始化 views视图 (6)

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.serializes import UserSerializer


# 需要认证才能访问的视图
def index(request):
    return HttpResponse("hello python!!!!")


# 分页(局部):自定义分页器 局部
class PageNum(PageNumberPagination):
    # 查询字符串中代表的每页返回数量的参数名,默认:None
    page_size_query_param = 'page_size'

    # 查询字符串中代表页码的参数名,有默认值:page
    # page_query_param='page'
    # 一页中最多的结果条数
    max_page_size = 2


# 自定义权限(局部)
class MyPermission(BasePermission):
    def has_permission(self, request, view):
        print(view.kwargs.get("pk"), request.user.id)
        '''判断用户对模型有没有访问权'''
        # 任何用户对使用此权限类的视图都有访问权限
        print(request)

        if request.user.is_superuser:
            # 管理员对用户模型有访问权
            return True

        elif view.kwargs.get('pk') == str(request.user.id):
            # 携带的id和用户的id相同时有访问权
            return True
        return False

    def has_object_permission(self, request, view, obj):
        '''获取单个数据时,判断用户对某个数据对象是否有访问权限'''
        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':
            pass
        else:
            return UserSerializer

上一篇:Vue+express项目优化上线(1)


下一篇:.NET core 2.0发布后没有 views视图页面文件