tornado3第二部分分析tornado處理路由__call__()

(代碼縮進(jìn)有點(diǎn)問題? 大家可以看源碼)

tornado有許多關(guān)于如何處理路由列表的源碼分析的博客维费,關(guān)鍵在與調(diào)用了Application.__call__函數(shù),然后遍歷路由列表汉买,取出對應(yīng)的處理類幔妨,由于處理類都是RequestHandler類榨惠,調(diào)用的是父類的_excute()進(jìn)行響應(yīng)處理厌衙,我們要了解的是__call__函數(shù)和什么時(shí)候調(diào)用了__call__函數(shù)

def __call__(self, request):

"""Called by HTTPServer to execute the request."""

transforms = [t(request) for t in self.transforms]

handler = None

args = []

kwargs = {}

handlers = self._get_host_handlers(request)

if not handlers:

handler = RedirectHandler(

self, request, url="http://" + self.default_host + "/")

else:

for spec in handlers:

match = spec.regex.match(request.path)

if match:

handler = spec.handler_class(self, request, **spec.kwargs)

if spec.regex.groups:

# None-safe wrapper around url_unescape to handle

# unmatched optional groups correctly

def unquote(s):

if s is None:

return s

return escape.url_unescape(s, encoding=None,

plus=False)

# Pass matched groups to the handler.? Since

# match.groups() includes both named and unnamed groups,

# we want to use either groups or groupdict but not both.

# Note that args are passed as bytes so the handler can

# decide what encoding to use.

if spec.regex.groupindex:

kwargs = dict(

(str(k), unquote(v))

for (k, v) in match.groupdict().items())

else:

args = [unquote(s) for s in match.groups()]

break

if not handler:

if self.settings.get('default_handler_class'):

handler_class = self.settings['default_handler_class']

handler_args = self.settings.get(

'default_handler_args', {})

else:

handler_class = ErrorHandler

handler_args = dict(status_code=404)

handler = handler_class(self, request, **handler_args)

# If template cache is disabled (usually in the debug mode),

# re-compile templates and reload static files on every

# request so you don't need to restart to see changes

if not self.settings.get("compiled_template_cache", True):

with RequestHandler._template_loader_lock:

for loader in RequestHandler._template_loaders.values():

loader.reset()

if not self.settings.get('static_hash_cache', True):

StaticFileHandler.reset()

handler._execute(transforms, *args, **kwargs)

return handler

當(dāng)http_server.listen(options.port)啟動(dòng)監(jiān)聽的時(shí)候兜粘,程序會accept socket.詳見netutil.add_accept_handler函數(shù),我們要注意傳遞的第一個(gè)參數(shù)_handle_connection是什么砸泛,是一個(gè)函數(shù)十籍,這里先不具體看函數(shù),我們看看到add_accept_handler后是怎么處理這些參數(shù)的

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

if self.io_loop is None:

self.io_loop = IOLoop.current()

for sock in sockets:

self._sockets[sock.fileno()] = sock

add_accept_handler(sock, self._handle_connection,

io_loop=self.io_loop)

def _handle_connection(self, connection, address):

if self.ssl_options is not None:

assert ssl, "Python 2.6+ and OpenSSL required for SSL"

try:

connection = ssl_wrap_socket(connection,

self.ssl_options,

server_side=True,

do_handshake_on_connect=False)

except ssl.SSLError as err:

if err.args[0] == ssl.SSL_ERROR_EOF:

return connection.close()

else:

raise

except socket.error as err:

if err.args[0] in (errno.ECONNABORTED, errno.EINVAL):

return connection.close()

else:

raise

try:

if self.ssl_options is not None:

stream = SSLIOStream(connection, io_loop=self.io_loop, max_buffer_size=self.max_buffer_size)

else:

stream = IOStream(connection, io_loop=self.io_loop, max_buffer_size=self.max_buffer_size)

self.handle_stream(stream, address)

except Exception:

app_log.error("Error in connection callback", exc_info=True)

#這是add_accept_handler(sock, self._handle_connection,io_loop=self.io_loop)

def add_accept_handler(sock, callback, io_loop=None):

"""Adds an `.IOLoop` event handler to accept new connections on ``sock``.

When a connection is accepted, ``callback(connection, address)`` will

be run (``connection`` is a socket object, and ``address`` is the

address of the other end of the connection).? Note that this signature

is different from the ``callback(fd, events)`` signature used for

`.IOLoop` handlers.

"""

if io_loop is None:

io_loop = IOLoop.current()

def accept_handler(fd, events):

while True:

try:

connection, address = sock.accept()

except socket.error as e:

# EWOULDBLOCK and EAGAIN indicate we have accepted every

# connection that is available.

if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN):

return

# ECONNABORTED indicates that there was a connection

# but it was closed while still in the accept queue.

# (observed on FreeBSD).

if e.args[0] == errno.ECONNABORTED:

continue

raise

callback(connection, address)

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

add_accept_handler(sock, callback, io_loop=None)函數(shù)接受request請求唇礁,調(diào)用了callback(connection,address)函數(shù)并且給IO事件循環(huán)注冊了一個(gè)事件勾栗,我們應(yīng)該知道callback()函數(shù)的,就是傳遞過來的參數(shù)_handle_connection()再看看這個(gè)函數(shù)做了什么處理分析不管前面做了什么處理盏筐,有一句是要執(zhí)行的self.handle_stream(stream, address)围俘,原來調(diào)用了HttpServer的

def handle_stream(self, stream, address):

HTTPConnection(stream, address, self.request_callback,

self.no_keep_alive, self.xheaders, self.protocol)

調(diào)用了HTTPConnection對象,很簡單机断,應(yīng)該只調(diào)用了構(gòu)造方法

看看Httpserver的構(gòu)造方法

def __init__(self, request_callback, no_keep_alive=False, io_loop=None,

xheaders=False, ssl_options=None, protocol=None, **kwargs):

self.request_callback = request_callback

self.no_keep_alive = no_keep_alive

self.xheaders = xheaders

self.protocol = protocol

TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options,

**kwargs)

def handle_stream(self, stream, address):

HTTPConnection(stream, address, self.request_callback,

self.no_keep_alive, self.xheaders, self.protocol)

request_callback是什么http_server = tornado.httpserver.HTTPServer(Application())這里清楚了是Application()楷拳,分析

def __init__(self, stream, address, request_callback, no_keep_alive=False,

xheaders=False, protocol=None):

self.stream = stream

self.address = address

# Save the socket's address family now so we know how to

# interpret self.address even after the stream is closed

# and its socket attribute replaced with None.

self.address_family = stream.socket.family

self.request_callback = request_callback

self.no_keep_alive = no_keep_alive

self.xheaders = xheaders

self.protocol = protocol

self._clear_request_state()

# Save stack context here, outside of any request.? This keeps

# contexts from one request from leaking into the next.

self._header_callback = stack_context.wrap(self._on_headers)

self.stream.set_close_callback(self._on_connection_close)

self.stream.read_until(b"\r\n\r\n", self._header_callback)

self._header_callback = stack_context.wrap(self._on_headers)這一句很關(guān)鍵,

def _on_headers(self, data):

#省略******

self.request_callback(self._request)

return

self.request_callback(self._request)前面說了吏奸,.request_callback=Application()所以request_callback(self._request) = Application()(self._request)類被當(dāng)做函數(shù)調(diào)用欢揖,所以__call__函數(shù)被調(diào)用了,就有了路由列表處理的操作奋蔚,比較繞啊

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末她混,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子泊碑,更是在濱河造成了極大的恐慌坤按,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,817評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件馒过,死亡現(xiàn)場離奇詭異臭脓,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)腹忽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,329評論 3 385
  • 文/潘曉璐 我一進(jìn)店門来累,熙熙樓的掌柜王于貴愁眉苦臉地迎上來砚作,“玉大人,你說我怎么就攤上這事嘹锁『迹” “怎么了?”我有些...
    開封第一講書人閱讀 157,354評論 0 348
  • 文/不壞的土叔 我叫張陵领猾,是天一觀的道長米同。 經(jīng)常有香客問我,道長摔竿,這世上最難降的妖魔是什么面粮? 我笑而不...
    開封第一講書人閱讀 56,498評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮继低,結(jié)果婚禮上但金,老公的妹妹穿的比我還像新娘。我一直安慰自己郁季,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,600評論 6 386
  • 文/花漫 我一把揭開白布钱磅。 她就那樣靜靜地躺著梦裂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪盖淡。 梳的紋絲不亂的頭發(fā)上年柠,一...
    開封第一講書人閱讀 49,829評論 1 290
  • 那天,我揣著相機(jī)與錄音褪迟,去河邊找鬼冗恨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛味赃,可吹牛的內(nèi)容都是我干的掀抹。 我是一名探鬼主播,決...
    沈念sama閱讀 38,979評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼心俗,長吁一口氣:“原來是場噩夢啊……” “哼傲武!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起城榛,我...
    開封第一講書人閱讀 37,722評論 0 266
  • 序言:老撾萬榮一對情侶失蹤揪利,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后狠持,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體疟位,經(jīng)...
    沈念sama閱讀 44,189評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,519評論 2 327
  • 正文 我和宋清朗相戀三年喘垂,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了甜刻。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绍撞。...
    茶點(diǎn)故事閱讀 38,654評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖罢吃,靈堂內(nèi)的尸體忽然破棺而出楚午,到底是詐尸還是另有隱情,我是刑警寧澤尿招,帶...
    沈念sama閱讀 34,329評論 4 330
  • 正文 年R本政府宣布矾柜,位于F島的核電站,受9級特大地震影響就谜,放射性物質(zhì)發(fā)生泄漏怪蔑。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,940評論 3 313
  • 文/蒙蒙 一丧荐、第九天 我趴在偏房一處隱蔽的房頂上張望缆瓣。 院中可真熱鬧,春花似錦虹统、人聲如沸弓坞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,762評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽渡冻。三九已至,卻和暖如春忧便,著一層夾襖步出監(jiān)牢的瞬間族吻,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,993評論 1 266
  • 我被黑心中介騙來泰國打工珠增, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留超歌,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,382評論 2 360
  • 正文 我出身青樓蒂教,卻偏偏與公主長得像巍举,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子凝垛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,543評論 2 349

推薦閱讀更多精彩內(nèi)容