django rest_framework 权限
在视图里面去设置权限
class OrderView(APIView):
authentication_classes = [MyAuthtication]
def get(self, request, *args, **kwargs):
ret = {"state_code": 1000, "msg": "数据请求成功", "data": ORDER_DICT}
if request.user.user_type != 3:
ret = {"state_code": 1001, "msg": "无权限", "data": []}
return JsonResponse(ret)
基本使用
class MyPermission(object):
def has_permission(self,request,view):
if request.user.user_type != 3:
return False
return True
class OrderView(APIView):
"""
订单相关业务(只有SVIP用户有权限)
"""
permission_classes = [MyPermission,]
def get(self,request,*args,**kwargs):
# request.user
# request.auth
self.dispatch
ret = {'code':1000,'msg':None,'data':None}
try:
ret['data'] = ORDER_DICT
except Exception as e:
pass
return JsonResponse(ret)
class MyPermission(object):
message = "无权访问"
def has_permission(self, request, view):
if request.user.user_type != 3:
return False
return True
源码流程
梳理:
- 使用
- 类,必须继承:BasePermission,必须实现:has_permission方法
from rest_framework.permissions import BasePermission
class SVIPPermission(BasePermission):
message = "必须是SVIP才能访问"
dehas_permission(self,request,view):
if request.useuser_type != 3:
return False
return True
class UserInfoView(APIView):
"""
订单相关业务(普通用户、VIP)
"""
permission_classes = [MyPermission1, ]
def get(self,request,*args,**kwargs):
return HttpResponse('用户信息')
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES":['api.utils.permission.SVIPPermission']
}