最近开始用restframework框架,刚一拿到项目完全是无数脸懵逼,所以接下来自己学习来对框架进行一些讲解,希望能够给初用框架的朋友带来一些帮助,错误和不足之处欢迎大家指出!
登录认证流程
1、请求进来先找APIView的dispatch
2、对request进行了封装
Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),#[BasicAuthentication()对象,]
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
#self.get_authenticators()#返回[BasicAuthentication()对象,]
#authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES#可以自己重写 自定义认证类
3、self.initial(request, *args, **kwargs)认证
4、self.perform_authentication()
def perform_authentication(self, request):
5、 request.user
6、request类里找user
def user():
7、self._authenticate()
循环认证类的所有对象
源码:
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
#循环遍历认证的所有对象
for authenticator in self.authenticators:
try:
#执行认证类的所有authenticate方法
#1、如果authenticate方法抛出异常,self._not_authenticated()执行,认证失败
#2、如果没有抛出异常,
#1、有返回值,必须是有两个元素的元组,(request.user,request.auth)函数结束,认证通过
#2、没有返回值,返回NONE,继续执行authentication_classes里面的下一个认证,如果都没有返回值,则执行self._not_authenticated(),self.user=AnonymousUser,self.auth=None ()
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()
8、执行自己写的authenticate方法
9、执行get/post/put/patch/…
#自定义的类放在views里是局部认证
2、全局使用认证
在settings里面写
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES":[自己定义得认证类]
#自己定义的认证类不要放在views里面,可以自己建一个文件夹放里面
#自己定义的认证类要写绝对路径
#'UNAUTHENTICATED_USER': lanbda:"匿名用户",
'UNAUTHENTICATED_USER': None,#匿名用户,request.user=None
'UNAUTHENTICATED_TOKEN': None,#匿名用户,request.user=None
}
全局都需要认证,当某一个类里面不需要认证时,比如第一次登陆,在这个类里面加上下面一句话就OK了
authentication_classes = []