执行过程 APIView() Ruquest() Authentication() OrderView()
APIView()
def duspatch:
self.initial(request)
def inital():
self.perform_authticate()
def perform_authticate():
request.user
Ruquest()
@
def user()
‘‘‘
def _authenticate()
循环所有authenticatior对象
执行对象的authenticate方法
Authentication 自定义认证类
def authenticate():
自定义认证类
-报错 raise exceptions.AuthenticationFailed("用户认证失败")
-返回元组(user对象, token对象)
print(request.user, request.auth)
OrderView
authentication_classes = [Authtication,]
def get():
...
def post()
...
Settinfs #全局使用#在api目录下创建个utils目录 创建个auth.py文件 将FirstAuthentication()添加
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES":[‘api.utils.auth.FirstAuthentication‘],
"UNAUTHENTICATED_USER":lambda:"匿名用户", #request.user 匿名用户的返回值
"UNAUTHENTICATED_USER":lambda:"None" #request.user 匿名用户的返回值为空
"UNAUTHENTICATED_TOKEN":lambda:"None" #request.auth 匿名用户的返回值为空
}
局部不使用
class AuthView(APIView):
authentication_class = []
def get(self,request, *args, **kwargs):
pass
内置的认证类
authentication.py文件中有以下几个类 BaseAuthentication(object)
class BaseAuthentication(object):
def authenticate(self,request)
def authenticate_header(self, request) #认证失败的话 给浏览器返回的相应头饿
return ‘Basic realm="%s"‘ % self.www_authenticate_realm
BasicAuthentication(BaseAuthentication) #是浏览器实现的 浏览器将用户和密码发给服务器
SessionAuthntication(BaseAuthentication) #不用
TokenAuthtication(BaseAuthntication) #不用
RemoteUserAuthentication(BaseAuthentication) #不用
暂时只用BaseAuthentication 创建类 继承BaseAuthentication
from rest_framework.authentication import BaseAuthentication
class FirstAuthentication(BaseAuthentication):
def authenticate(self, request):
pass
#这样就可以实现认证功能了
原文:https://www.cnblogs.com/Liang-jc/p/9383796.html