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)

 

實際上就是等待客戶端事件的函數

相關文章
相關標籤/搜索