您的位置:首页 > 编程语言 > Go语言

Django 之REST framework学习:Authentication认证流程源码剖析

2018-02-05 15:42 806 查看
首先请求进来会执行APIView.dispatch():

class APIView(View):
def dispatch(self, request, *args, **kwargs):

self.args = args
self.kwargs = kwargs
#初始化request,封装认证等对象列表
"""
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
"""
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers  # deprecate?

try:
#在请求方法处理之前调用的一些方法:比如版本,认证,权限,节流四部:
self.initial(request, *args, **kwargs)

# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed

response = handler(request, *args, **kwargs)

except Exception as exc:
response = self.handle_exception(exc)
#处理返回值并最终返回
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response


下面我们应该主要看下
self.initial()


self.initial(request, *args, **kwargs)

def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)

# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg

# Determine the API version, if versioning is in use.
#版本信息处理
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme

# Ensure that the incoming request is permitted
#认证信息处理(我们主要看的地方)
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)


接着我们看下
self.perform_authentication(request)


def perform_authentication(self, request):
request.user


找到
Request
类中的
user
属性方法,最终会执行
self._authenticate()


class Request(object):
@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate()
return self._user


下一步:

def _authenticate(self):
#遍历Request类中封装的self.authenticators(这个是前面initialize_request封装的对象列表),
#分别执行authenticate方法,成功返回self.user, self.auth;失败抛异常:APIException。
for authenticator in self.authenticators:
try:
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


以上就是整个的Authentication认证流程,其他流程包括权限和节流都是一样的套路,这样我们懂了认证流程后就可以自定制认证流程了,自定制认证流程代码先不上了,等抽空补上!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Django REST framework