1.入口:wsgi.py
2.WSGIHandler类 实例化调用__init__方法
3.父类 BaseHandler 中的 load_middleware()方法
4.判断settings中MIDDLEWARE是否为空 一般我们的中间件不为空 走else分支
5.上图中 self._get_response
# django/core/handlers/base.py def _get_response(self, request): 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) # 这个callback就是我们的视图函数, 后两个是视图函数可能需要的参数 callback, callback_args, callback_kwargs = resolver_match request.resolver_match = resolver_match # 应用 view middleware 中间件 for middleware_method in self._view_middleware: response = middleware_method(request, callback, callback_args, callback_kwargs) # 只要有response返回, 就立刻停止遍历 if response: break if response is None: # 给视图函数包装一层 wrapped_callback = self.make_view_atomic(callback) try: # 这里是调用视图函数 response = wrapped_callback(request, *callback_args, **callback_kwargs) except Exception as e: # 有异常就进入exception view处理 response = self.process_exception_by_middleware(e, request) # 这个不常用的process_template_response功能, 看源码可以清楚的知道为什么 # 返回的结果为啥需要有render方法了 elif hasattr(response, 'render') and callable(response.render): for middleware_method in self._template_response_middleware: response = middleware_method(request, response) # ... try: response = response.render() except Exception as e: response = self.process_exception_by_middleware(e, request) return response