Django WSGI响应过程之WSGIHandler

class WSGIHandler(base.BaseHandler):
    request_class = WSGIRequest

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.load_middleware() #载入中间件装饰器

    def __call__(self, environ, start_response):#每次请求被调用
        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        request = self.request_class(environ)  #获取WSGIrequest对象,保存header
        response = self.get_response(request)  #获取response对象,见下方

        response._handler_class = self.__class__

        status = '%d %s' % (response.status_code, response.reason_phrase)   #准备返回状态
        response_headers = [
            *response.items(),
            *(('Set-Cookie', c.output(header='')) for c in response.cookies.values()),
        ]  #准备返回header
        start_response(status, response_headers)  #返回响应体
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response
handlers/base中:
def get_response(self, request):
    """Return an HttpResponse object for the given HttpRequest."""
    # Setup default url resolver for this thread
    set_urlconf(settings.ROOT_URLCONF)  #设置urls/base.py中的_urlconf.value
    response = self._middleware_chain(request)  #依次调用中间件后返回response
    response._closable_objects.append(request)
    if response.status_code >= 400: #异常处理
        log_response(
            '%s: %s', response.reason_phrase, request.path,
            response=response,
            request=request,
        )
    return response

 

上一篇:Django 框架学习(七):用户认证、项目部署、WSGI Dhango工作环境部署、nginx反向代理配置


下一篇:雷林鹏分享Flask部署