tornado4.0.2源码简要分析2

1) 建立application 对象linux

application = tornado.web.Application([web

(r"/", MainHandler),app

])socket

 

此时咱们传入的参数为 handler列表函数

在 Application::__init__中调用tornado

   if handlers:oop

   self.add_handlers(".*$", handlers)spa

而后咱们来看add_handlersserver

def add_handlers(self, host_pattern, host_handlers):对象

handlers = [] ‘’’初始化handler列表’’’

if self.handlers and self.handlers[-1][0].pattern == '.*$':

self.handlers.insert(-1, (re.compile(host_pattern), handlers))

else:

self.handlers.append((re.compile(host_pattern), handlers))

for spec in host_handlers:

...........

handlers.append(spec) ‘’’host_handlers中的对象添加到handlers’’’

此时 Application 的 handlers中就有了handlers全部的对象

 

 

2) Httpserver的初始化和建立监听对象

 

一) 处理对象的传递

 

先看httpserver的初始化

server = HTTPServer(self, **kwargs)

传入的参数为: Application 同时Application HTTPServerConnectionDelegate的子类

 

初始化:self.request_callback = request_callback

此时的request_callback就是 application对象

 

二) 监听对象

 

application.listen(8888) 建立监听对象,先看代码

def listen(self, port, address="", **kwargs):

from tornado.httpserver import HTTPServer

server = HTTPServer(self, **kwargs) #建立httpserver对象

server.listen(port, address) #调用serverlisten

 

HTTPServer 有几种方式来工做,只看了其中一种

Httpserver继承自TCPServer

Server.listen调用的就是 TCPServerlisten方法

 

def listen(self, port, address=""):

        """Starts accepting connections on the given port.

 

        This method may be called more than once to listen on multiple ports.

        `listen` takes effect immediately; it is not necessary to call

        `TCPServer.start` afterwards.  It is, however, necessary to start

        the `.IOLoop`.

        """

        sockets = bind_sockets(port, address=address)

        self.add_sockets(sockets)

 

bind_sockets 建立监听对象

add_sockets 用来将监听对象放到ioloop中进行监控

Add_sockets 调用 add_accept_handler

先检测io_loop对象是否为空

if io_loop is None:

    io_loop = IOLoop.current() 

说明:

#此时若是是在linux环境下,io_loop其实是EPollIOLoop对象

io_loop.add_handler(sock, accept_handler, IOLoop.READ)

将监听对象放到io_loop

调用的是:PollIOLoop::add_handler

设置的事件回调函数为:

accept_handler

 

而后调用

tornado.ioloop.IOLoop.instance().start()

上面调用的就是 PollIOLoop::start()

代码细节没关注:

while True:

。。。。。。。。。。。。。。。。。。。。。

event_pairs = self._impl.poll(poll_timeout)

 

实际上就是等待客户端事件的函数

相关文章
相关标签/搜索