1 def _get_response(self, request): 2 """ 3 Resolve and call the view, then apply view, exception, and 4 template_response middleware. This method is everything that happens 5 inside the request/response middleware. 6 """ 7 response = None 8 9 if hasattr(request, 'urlconf'): 10 urlconf = request.urlconf 11 set_urlconf(urlconf) 12 resolver = get_resolver(urlconf) 13 else: 14 resolver = get_resolver() 15 resolver_match = resolver.resolve(request.path_info) 16 callback, callback_args, callback_kwargs = resolver_match 17 request.resolver_match = resolver_match 18 19 for middleware_method in self._view_middleware: 20 21 """ 22 <bound method 23 CsrfViewMiddleware.process_view of 24 <django.middleware.csrf.CsrfViewMiddleware object at 0x034B1388>> 25 """ 26 response = middleware_method(request, callback, callback_args, callback_kwargs) 27 if response: 28 break 30 if response is None: 31 wrapped_callback = self.make_view_atomic(callback) 32 try: 33 34 response = wrapped_callback(request, *callback_args, **callback_kwargs) 35 except Exception as e: 36 response = self.process_exception_by_middleware(e, request) 37 38 # Complain if the view returned None (a common error). 40 if response is None: 41 if isinstance(callback, types.FunctionType): # FBV 42 view_name = callback.__name__ 43 else: # CBV 44 view_name = callback.__class__.__name__ + '.__call__' 45 46 raise ValueError( 47 "The view %s.%s didn't return an HttpResponse object. It " 48 "returned None instead." % (callback.__module__, view_name) 49 ) 50 51 # If the response supports deferred rendering, apply template 52 # response middleware and then render the response 53 elif hasattr(response, 'render') and callable(response.render): 54 for middleware_method in self._template_response_middleware: 55 response = middleware_method(request, response) 56 # Complain if the template response middleware returned None (a common error). 57 if response is None: 58 raise ValueError( 59 "%s.process_template_response didn't return an " 60 "HttpResponse object. It returned None instead." 61 % (middleware_method.__self__.__class__.__name__) 62 ) 63 64 try: 65 response = response.render() 66 except Exception as e: 67 response = self.process_exception_by_middleware(e, request) 68 return response
图解:
在执行完slef._get_response()后,程序会继续执行_middlware_chain 函数栈中的process_response
总结:关于中间件中的request/response