DRF之权限
操作步骤
第一步:
写一个类,继承BasePermission,重写has_permission,判断如果有权限,返回True,如果没有权限,返回False
第二步:局部使用和全局使用
局部使用
class BookDetailView(GenericViewSet, CreateModelMixin, DestroyModelMixin, UpdateModelMixin): permission_classes = [UserPermission, ]
全局使用
REST_FRAMEWORK={ "DEFAULT_PERMISSION_CLASSES":["app01.auth.UserPermission",] }
代码(需要先登录)
auth.py
from rest_framework.permissions import BasePermission class UserPermission(BasePermission): def has_permission(self, request, view): # self.message = '你是普通用户,没有权限' # 没有权限,提示信息 self.message = '你是%s用户,没有权限' % request.user.get_user_type_display() # 没有权限,提示信息 # 如果有权限返回True,没有权限返回False # 权限类,在认证类知之后,request.user有了当前登录用户 user_type = request.user.user_type if user_type < 3: # 只要不是1和2,就没有权限 return True else: return False
views.py
from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin, RetrieveModelMixin, \ UpdateModelMixin # 普通用户只能查看 class BookView(GenericViewSet, ListModelMixin, RetrieveModelMixin): authentication_classes = [LoginAuth, ] queryset = Book.objects.all() serializer_class = BookSerializer from .auth import UserPermission # 普通用户及以上才能修改 class BookDataView(GenericViewSet, CreateModelMixin, DestroyModelMixin): authentication_classes = [LoginAuth, ] permission_classes = [UserPermission, ] queryset = Book.objects.all() serializer_class = BookSerializer
urls.py
from django.urls import path, include from app01 import views from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register('user', views.UserView, 'user') router.register('books', views.BookView, 'books') router.register('booksdata', views.BookDataView, 'booksdata') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), ]
代码需求说明
# 登录成功----》所有必须登录能访问---》每个视图类上加认证类 # 用户是普通用户---》普通用户可以访问所有和单条 # 普通管理员和超级用户可以操作所有,除了访问单条和所有的那个视图类,加上认证类 # books:查看一条,和所有 # booksdata路由下有:删除,新增,修改---》权限类加在这里 # book 5个接口,必须登录才能访问 # 5个接口分成了俩视图写: -BookView:获取所有,获取单条 -BookDetailView:删除,修改,新增 -这俩视图都需要登录:authentication_classes = [LoginAuth, ] -BookView只要登陆就可以操作 -BookDetailView必须有权限才能,加了一个权限,permission_classes = [UserPermission, ]