Django middleware initialization process (draft)

load_middleware DEF (Self): 
"" "
. Middleware Lists from the Populate settings.MIDDLEWARE

Must BE Called After Environment The IS Fixed (See the __call__ in subclasses).
" ""
self._view_middleware = []
self._template_response_middleware = []
self._exception_middleware = []

Handler = convert_exception_to_response (self._get_response) # view function to return, one packet error exception handling function. If an error occurs, it returns an error response, if not wrong, things return _get_response return
for middleware_path in the reversed (settings.MIDDLEWARE):
Middleware = import_string (middleware_path)
the try:
mw_instance = Middleware (Handler)
the except MiddlewareNotUsed AS EXC:
IF Settings. DEBUG:
if str(exc):
logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
else:
logger.debug('MiddlewareNotUsed: %r', middleware_path)
continue

if mw_instance is None:
raise ImproperlyConfigured(
'Middleware factory %s returned None.' % middleware_path
)

if hasattr(mw_instance, 'process_view'):
self._view_middleware.insert(0, mw_instance.process_view)
if hasattr(mw_instance, 'process_template_response'):
self._template_response_middleware.append(mw_instance.process_template_response)
if hasattr(mw_instance, 'process_exception'):
self._exception_middleware.append(mw_instance.process_exception)

handler = convert_exception_to_response(mw_instance)

# We only assign to this when initialization is complete as it is used
# as a flag for initialization being complete.
self._middleware_chain = handler


def _get_response(self, request):
"""
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
"""
response = None

if hasattr(request, 'urlconf'):
urlconf = request.urlconf
set_urlconf(urlconf)
resolver = get_resolver(urlconf)
else:
resolver = get_resolver()

resolver_match = resolver.resolve(request.path_info) #从请求url获取视图
callback, callback_args, callback_kwargs = resolver_match #获取视图函数,以及传参
request.resolver_match = resolver_match

# Apply view middleware
middleware_method in self._view_middleware for:
the Response = middleware_method (Request, callback, callback_args, callback_kwargs) # call the view before calling the middleware view, note that if there is the return response, will not call the view function
IF the Response:
BREAK

IF IS the Response None:
wrapped_callback = self.make_view_atomic (callback) # transaction for each view a package
the try:
Response = wrapped_callback (Request, callback_args *, ** callback_kwargs) # view function calls
the except Exception aS E:
Response = self.process_exception_by_middleware (E, Request)

after the response returned # Complain if the view returned None (a common error) # call exception handling view is empty.
IF response None iS:
IF the isinstance (the callback, types.FunctionType): # the FBV
view_name = callback.__name__
else: # CBV
view_name = callback.__class__.__name__ + '.__call__'

raise ValueError(
"The view %s.%s didn't return an HttpResponse object. It "
"returned None instead." % (callback.__module__, view_name)
)

# If the response supports deferred rendering, apply template
# response middleware and then render the response
elif hasattr(response, 'render') and callable(response.render):
for middleware_method in self._template_response_middleware:
response = middleware_method(request, response)
# Complain if the template response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_template_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__)
)

try:
response = response.render()
except Exception as e:
response = self.process_exception_by_middleware(e, request)

return response




Guess you like

Origin www.cnblogs.com/EmptyRabbit/p/11390299.html