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

(代码缩进有点问题  大家可以看源码)

tornado有许多关于如何处理路由列表的源码分析的博客,关键在与调用了Application.__call__函数,然后遍历路由列表,取出对应的处理类,由于处理类都是RequestHandler类,调用的是父类的_excute()进行响应处理,我们要了解的是__call__函数和什么时候调用了__call__函数

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

当http_server.listen(options.port)启动监听的时候,程序会accept socket.详见netutil.add_accept_handler函数,我们要注意传递的第一个参数_handle_connection是什么,是一个函数,这里先不具体看函数,我们看看到add_accept_handler后是怎么处理这些参数的

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)函数接受request请求,调用了callback(connection,address)函数并且给IO事件循环注册了一个事件,我们应该知道callback()函数的,就是传递过来的参数_handle_connection()再看看这个函数做了什么处理分析不管前面做了什么处理,有一句是要执行的self.handle_stream(stream, address),原来调用了HttpServer的

def handle_stream(self, stream, address):

HTTPConnection(stream, address, self.request_callback,

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

调用了HTTPConnection对象,很简单,应该只调用了构造方法

看看Httpserver的构造方法

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)这一句很关键,

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)类被当做函数调用,所以__call__函数被调用了,就有了路由列表处理的操作,比较绕啊

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,076评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,658评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,732评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,493评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,591评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,598评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,601评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,348评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,797评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,114评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,278评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,953评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,585评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,202评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,442评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,180评论 2 367
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,139评论 2 352

推荐阅读更多精彩内容