# Note: Views are made CSRF exempt from within `as_view` as to prevent
# accidental removal of this exemption in cases where `dispatch` needs to
# be overridden.
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
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
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(), #解析get请求
authenticators=self.get_authenticators(), #认证相关
negotiator=self.get_content_negotiator(), # 选择相关
parser_context=parser_context
)
initialize_request
方法中,有一个方法处理过request,view的值是self,代指的是UsersView这个对象,所以get_parser_context方法把UsersView这个类封装进来然后返回,所以get_parser_context方法最后返回的当前对象以及当前对象所传的参数。 def get_parser_context(self, http_request):
"""
Returns a dict that is passed through to Parser.parse(),
as the `parser_context` keyword argument.
"""
# Note: Additionally `request` and `encoding` will also be added
# to the context by the Request object.
return {
'view': self,
'args': getattr(self, 'args', ()),
'kwargs': getattr(self, 'kwargs', {})
}
def get_authenticators(self):
"""
Instantiates and returns the list of authenticators that this view can use.
"""
return [auth() for auth in self.authentication_classes]
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
DEFAULTS = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
),
}
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.
# 如果url中有版本信息,就获取发送到服务端的版本,返回一个元组
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Ensure that the incoming request is permitted
# 执行认证功能,确认进行后续操作的用户是被允许的.perform_authentication方法返回经过认证的用户对象
self.perform_authentication(request)
# 如果用户通过认证,检查用户是否有权限访问url中所传的路径.如用用户访问的是没有没有权限的路径,则会抛出异常.
self.check_permissions(request)
# check_throttles方法的作用是检查用户是否被限制了访问主机的次数,如果用户访问服务器的次数超出设定值,则会抛出一个异常
self.check_throttles(request)
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
def finalize_response(self, request, response, *args, **kwargs):
"""
Returns the final response object.
"""
# Make the error obvious if a proper response is not returned
assert isinstance(response, HttpResponseBase), (
'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
'to be returned from the view, but received a `%s`'
% type(response)
)
if isinstance(response, Response):
if not getattr(request, 'accepted_renderer', None):
neg = self.perform_content_negotiation(request, force=True)
request.accepted_renderer, request.accepted_media_type = neg
response.accepted_renderer = request.accepted_renderer
response.accepted_media_type = request.accepted_media_type
response.renderer_context = self.get_renderer_context()
# Add new vary headers to the response instead of overwriting.
vary_headers = self.headers.pop('Vary', None)
if vary_headers is not None:
patch_vary_headers(response, cc_delim_re.split(vary_headers))
for key, value in self.headers.items():
response[key] = value
return response
1.请求到达服务端,经过WSGI和中间件到达路由系统
2.路由系统执行配置的CBV或者FBV中的dispatch方法
3.在dispatch方法中,request方法被封装添加了解析器,认证方法及选择器等方法
4.然后执行initial方法
5.再获取版本,进行认证操作,权限操作和节流操作
6.最后执行自定义的get,post,push,delete等自定义方法
7.在执行initial方法之前,通过try来捕获可能出现的异常
8.如果出现异常,就执行handle_exception方法来处理捕获到的异常
9.不管是否出现异常,最后的返回值都通过finalize_response方法来处理响应的内容
源码剖析Django REST framework的请求生命周期