声明:
本博客欢迎转发,但请保留原作者信息!内容系本人学习、研究和总结,如有雷同,实属荣幸!
原文地址:http://blog.csdn.net/gtt116/
上一期讲解了WSGI处理思路,本文将分析django如何实现此接口。
在此模块中着重看两个文件:base.py, wsgi.py
首先从宏观上看主要涉及到的类:
而当我们运行了manage.py runserver后,将会生成一个进程来运行WSGIHandler实例,来响应用户的请求,其实WSGIHandler就是一个上篇提到的app。
好了,现在关键就是WSGIHandler的__call__方法。
代码如下(可暂时略过):
def __call__(self, environ, start_response): from django.conf import settings # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._request_middleware is None: self.initLock.acquire() try: try: # Check that middleware is still uninitialised. if self._request_middleware is None: self.load_middleware() except: # Unload whatever middleware we got self._request_middleware = None raise finally: self.initLock.release() set_script_prefix(base.get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: try: request = self.request_class(environ) except UnicodeDecodeError: logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path, exc_info=sys.exc_info(), extra={ 'status_code': 400, 'request': request } ) response = http.HttpResponseBadRequest() else: response = self.get_response(request) finally: signals.request_finished.send(sender=self.__class__) try: status_text = STATUS_CODE_TEXT[response.status_code] except KeyError: status_text = 'UNKNOWN STATUS CODE' status = '%s %s' % (response.status_code, status_text) response_headers = [(str(k), str(v)) for k, v in response.items()] for c in response.cookies.values(): response_headers.append(('Set-Cookie', str(c.output(header='')))) start_response(status, response_headers) return response
django把middleware分为了5类,分别是:
request_middleware
view_middleware
template_response_middleware
response_middleware
exception_middleware
django通过类中的对应的方法判断属于哪个类别
源码如下:
for middleware_path in settings.MIDDLEWARE_CLASSES: mw_class = import_string(middleware_path) try: mw_instance = mw_class() except MiddlewareNotUsed: continue if hasattr(mw_instance, 'process_request'): request_middleware.append(mw_instance.process_request) if hasattr(mw_instance, 'process_view'): self._view_middleware.append(mw_instance.process_view) if hasattr(mw_instance, 'process_template_response'): self._template_response_middleware.insert(0, mw_instance.process_template_response) if hasattr(mw_instance, 'process_response'): self._response_middleware.insert(0, mw_instance.process_response) if hasattr(mw_instance, 'process_exception'): self._exception_middleware.insert(0, mw_instance.process_exception) # We only assign to this when initialization is complete as it is used # as a flag for initialization being complete. self._request_middleware = request_middleware
类别 |
方法 |
request_middleware |
process_request |
view_middleware |
process_view |
template_response_middleware |
process_template_response |
response_middleware |
process_response |
exception_middleware |
process_exception |
所以django的处理路径如下图所示:
Request_middle → View_middleware → View → Exception_middleware → template_response_middleware → Response_middleware
其实django就是使用一个handler作为一个wrapper将所有的app,middleware包裹在一起,并且按照上面的顺序进行处理,这样的好处是:
思路清晰,利于代码的维护,便于代码的扩展,并且将各个相对独立的步骤分割开来,互不影响。