首先请求进来会执行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