(tornado源码分析_004)HTTP服务器处理解析出来的http数据
Posted madun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(tornado源码分析_004)HTTP服务器处理解析出来的http数据相关的知识,希望对你有一定的参考价值。
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数据的主要内容,如果未能解决你的问题,请参考以下文章
Tornado 高并发源码分析之三--- Application 对象
Tornado 高并发源码分析之四--- HTTPServer 与 TCPServer 对象