认证组件 1 写一个认证类 from rest_framework.authentication import BaseAuthentication class MyAuth(BaseAuthentication): def authenticate(self,request): # request 是封装后的 token = request.query_params.get('token') ret = models.UserToken.objects.filter(token=token).first() if ret: # 认证通过 return else: raise AuthenticationFailed('认证失败') #可以不写了 def authenticate_header(self,ss): pass 2 局部使用 authentication_classes=[MyAuth,MyAuth2] 3 全局使用 查找顺序:自定义的APIView里找---》项目settings里找---》内置默认的 REST_FRAMEWORK={ 'DEFAULT_AUTHENTICATION_CLASSES':['utils.common.MyAuth',] } 权限组件 1 写一个类 from rest_framework.permissions import BasePermission class MyPermission(BasePermission): message = '不是超级用户,查看不了' def has_permission(self,request,view): token=request.query_params.get('token') ret=models.UserToken.objects.filter(token=token).first() if ret.user.type==2: # 超级用户可以访问 return True else: return False 2 局部使用: permission_classes=[MyPermission,] 3 全局使用: REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':['utils.common.MyPermission',] } 频率组件 1 写一个类: from rest_framework.throttling import SimpleRateThrottle class VisitThrottle(SimpleRateThrottle): scope = 'xxx' def get_cache_key(self, request, view): return self.get_ident(request) 2 在setting里配置: 'DEFAULT_THROTTLE_RATES':{ 'xxx':'5/h', } 3 局部使用 throttle_classes=[VisitThrottle,] 4 全局使用 REST_FRAMEWORK={ 'DEFAULT_THROTTLE_CLASSES':['utils.common.VisitThrottle',] }
认证组件,权限组件,频率组件
猜你喜欢
转载自www.cnblogs.com/xujinjin18/p/9833923.html
今日推荐
周排行