详细方法参考Django官方授权API
1.全局权限
在setting
中配置授权管理,这个授权是全局的,对于每一个视图都生效
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
2. 视图级别权限
2.1 给所有功能授权同样权限
shop.viess.py
代码
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from shop.models import Category, Goods
from shop.serializers import CategorySerializer, GoodsSerializer
class CategoryViewSets(viewsets.ModelViewSet):
"""
分类视图:
继承ModelViewSet之后拥有GET POST PUT PATCH DELETE等HTTP动词操作
serilizer_class 指明序列化类
"""
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_classes = [IsAdminUser,IsAuthenticated]
没有授权的时候的显示:
在Apifox或者postman中使用管理员账户登入测试
选择BasicAuth
,使用管理员账户登入之后就可以查询到结果
2.2.根据不同身份对同一个视图设置不同的权限
需求:超级管理员可以创建分类 普通用户可以查看分类
shop.view.py
代码:
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from shop.models import Category, Goods
from shop.serializers import CategorySerializer, GoodsSerializer
class CategoryViewSets(viewsets.ModelViewSet):
"""
分类视图:
继承ModelViewSet之后拥有GET POST PUT PATCH DELETE等HTTP动词操作
serilizer_class 指明序列化类
"""
queryset = Category.objects.all()
serializer_class = CategorySerializer
def get_permissions(self):
if self.action == "create" or self.action == "update" or self.action == "partial_update" or self.action == "destroy":
return [IsAdminUser()]
else:
return []
效果演示,使用普通用户登入,然后添加商品分类:
就会报错没有权限进行添加操作
2.3.自定义权限
在子app下面创建一个权限类shop.permission.py
"""
自定义权限
"""
from rest_framework import permissions
class CategorysPermission(permissions.BasePermission):
def has_permission(self, request, view):
return False
在views.py
中引用这个自定义视图类
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from shop import permissions
from shop.models import Category, Goods
from shop.serializers import CategorySerializer, GoodsSerializer
class CategoryViewSets(viewsets.ModelViewSet):
"""
分类视图:
继承ModelViewSet之后拥有GET POST PUT PATCH DELETE等HTTP动词操作
serilizer_class 指明序列化类
"""
queryset = Category.objects.all()
serializer_class = CategorySerializer
def get_permissions(self):
if self.action == "create" or self.action == "update" or self.action == "partial_update" or self.action == "destroy":
return [permissions.has_permission()]
else:
return []
3.模型级别权限