2.3 认证组件的使用
作者:互联网
# 写一个认证类 app_auth.py from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from app01.models import UserToken class MyAuthentication(BaseAuthentication): def authenticate(self, request): # 认证逻辑,如果认证通过,返回两个值 #如果认证失败,抛出AuthenticationFailed异常 token=request.GET.get('token') if token: user_token=UserToken.objects.filter(token=token).first() # 认证通过 if user_token: return user_token.user,token else: raise AuthenticationFailed('认证失败') else: raise AuthenticationFailed('请求地址中需要携带token') # 可以有多个认证,从左到右依次执行 # 全局使用,在setting.py中配置 REST_FRAMEWORK={ "DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",] } # 局部使用,在视图类上写 authentication_classes=[MyAuthentication] # 局部禁用 authentication_classes=[]
标签:AuthenticationFailed,authentication,认证,组件,token,user,2.3,import 来源: https://www.cnblogs.com/dzs894330350/p/16104788.html