认证组件格式:
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import APIException from .models import UserToken # 1、定义认证类 class UserAuth(BaseAuthentication): # 所有的认证逻辑都在authenticate def authenticate(self, request): user_token = request.query_params.get("token") # print('request.query_params:',request.query_params) # print('request.GET',request.GET) #request.query_params和request.GET打印的结果一样 try: token = UserToken.objects.get(token=user_token) # 后面权限会用到 return token.user, token.token except Exception: raise APIException("没有认证") 2 、局部使用 authentication_classes=[UserAuth,MyAuth2] #注意:当有多个认证类时,返回值必须写在最后一个认证类中 3 、全局使用 查找顺序:自定义的APIView里找---》项目settings里找---》内置默认的 REST_FRAMEWORK={ 'DEFAULT_AUTHENTICATION_CLASSES':['utils.common.UserAuth',] }
权限组件格式:
#1 写一个类 class MyPermission(): 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' #全局用scope,局部的可以用rate='5/s',如果用rate就不需要在settings里面配置 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.MyPermission',] }