django源码笔记-【2】(转)

add by zhj: 在原文的基础上有修改

原文:http://www.cnblogs.com/gaott/archive/2012/02/28/2371238.html

上一期完理解了WSGI处理思路,现在看看django是如何实现这个接口的。

django.core.handlers

在此模块中着重看两个文件:base.py, wsgi.py

首先从宏观上看主要涉及到的类:

而当我们运行了manage.py runserver后,将会生成一个进程来运行WSGIHandler实例,来响应用户的请求,其实WSGIHandler就是一个上篇提到的handler。

好了,现在关键就是WSGIHandler的__call__方法。

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

 

由代码我们知道

djangomiddleware分为了5类,分别是:

  1. request_middleware

  2. view_middleware

  3. template_response_middleware

  4. response_middleware

  5. exception_middleware

     

django通过类中的对应的方法判断属于哪个类别

 

类别

方法

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

 add by zhj: 右边这张图加入了Django Rest Framework的处理流程

 

其实django就是使用一个WSGIHandler作为wrapper,将所有的app,middleware包裹在一起,并且按照上面的顺序进行处理,这样的好处是:

思路清晰,利于代码的维护,便于代码的扩展,并且将各个相对独立的步骤分割开来,互补影响。

完整的流程图如下

              

 

posted @ 2014-04-04 15:23  奋斗终生  Views(593)  Comments(0Edit  收藏  举报