码迷,mamicode.com
首页 > Web开发 > 详细

(tornado源码分析_004)HTTP服务器处理解析出来的http数据

时间:2018-08-24 20:44:58      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:tar   处理   完整   size   soc   compress   调用   启动方式   ESS   

tornado中HTTP服务器是承上启下的作用,它通过tornado.http1connection.HTTP1ServerConnection与tornado.http1connection.HTTP1Connection从socket中读取并解析http消息

然后调用application处理解析出来的http消息,具体方法为:将application作为数据处理类传给上述两个读取数据的类

具体代码如下

#常见的torando启动方式
application = tornado.web.Application(Handlers)
application.listen(8888) 

class Application(ReversibleRouter):
    def listen(self):
        #启动时创建HTTPServer
        from tornado.httpserver import HTTPServer
        server = HTTPServer(self, **kwargs)
        server.listen(port, address)
        return server

class HTTPServer(TCPServer,Configurable,httputil.HTTPServerConnectionDelegate):   
    def __init__(self, application):
        #将application包装成_CallableAdapter,因为application负责处理完整的request,
        self.delegate = _CallableAdapter(application)

class HTTP1Connection(httputil.HTTPConnection):
    def read_response(self, delegate):
        if self.params.decompress:
            delegate = _GzipMessageDelegate(delegate, self.params.chunk_size)
        return self._read_message(delegate)

    def _read_message(self, delegate):
        #调用上层即HTTPServer处理解析出来的http消息头部,该处理也是异步的
        delegate.headers_received(start_line, headers)
    
    def _read_body(self, code, headers, delegate):
        #body可能较大,时分片到达的
        delegate.data_received(chunk)

class _CallableAdapter(httputil.HTTPMessageDelegate):
    def __init__(self, request_callback, request_conn):
        self.connection = request_conn
        self.request_callback = request_callback
        self.request = None
        self.delegate = None
        self._chunks = []

    def headers_received(self, start_line, headers):
        #当代用该函数时,说明是一个新的请求,创建request
        self.request = httputil.HTTPServerRequest(
            connection=self.connection, start_line=start_line,
            headers=headers)

    def data_received(self, chunk):
        #body是分片到达的,保存,以便最后组装
        self._chunks.append(chunk)

    def finish(self):
        #组装body
        self.request.body = b‘‘.join(self._chunks)
        self.request._parse_body()
        
        #调用application(tornado的web框架)处理request
        self.request_callback(self.request)

    def on_connection_close(self):
        self._chunks = None

 

(tornado源码分析_004)HTTP服务器处理解析出来的http数据

标签:tar   处理   完整   size   soc   compress   调用   启动方式   ESS   

原文地址:https://www.cnblogs.com/madun/p/9531758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!