Rest Framework 之权限组件

restful权限控制

# 写一个权限类,继承BasePermission
class MyPremission(BasePermission):
    # 重写has_premission方法
    message = "中文错误信息" # 读源码可以知道 返回值显示中文,写message ="中文"
    def has_premission(self,request,view):
        # 下面写权限控制相关逻辑
        # 因为权限校验在认证之后,所以能取到request.user
        if request.user。user_type == 1:
            return True # 查看源码发现 返回值是bool值
        else:
            return False

权限组件的使用

  1. 在局部视图中使用

    在视图类中写

    permission_classes=[MyPermision,]
  2. 全局使用

    需要在setting.py中配置

    REST_FRAMEWORK={
         "DEFAULT_PERMISSION_CLASSES":["app01.MyAuths.MyPermision",]
             }
  3. 全局设置后,在局部禁用

    # 在视图类中写
    permission_classes = []

猜你喜欢

转载自www.cnblogs.com/majingjie/p/11128494.html
今日推荐