tornado 自动加载 autoreload

在用tornado进行 网络程序编写的时候,肯定要对代码进行修修改改,如果每次都要重启server的话,会是很麻烦的事情。tornado提供了autoreload模式。

可以看到一个私有方法:_reload_on_update,其实只要引入这个模块,调用它即可。示例如下:

import tornado.autoreload
def main():
    server = tornado.httpserver.HTTPServer(application)
    server.listen(8888)
    instance = tornado.ioloop.IOLoop.instance()
    tornado.autoreload.start(instance)
    instance.start()

这样还是很麻烦,或者通过option参数来选择是否autoreload。偶然查看其 web.py 1000多行有这么一句:

        # Automatically reload modified modules
        if self.settings.get("debug") and not wsgi:
            import autoreload
            autoreload.start()

这个是读取Application里settings是否有debug变量,有则调用autoreload。简化后代码如下:

 settings = {'debug' : True}

 application = tornado.web.Application([
     (r"/", MainHandler),
     ], **settings)

def main():
    server = tornado.httpserver.HTTPServer(application)
    server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

一,要开始autoreload模式,可以在setting中进行设置,可以将debug模式开启,debug模式开启时,autoreload模式会自动开启;当然也可以显示的设置autoreload为True;或者可以debug=True,autoreload=False;

........

if self.settings.get('debug'):
    self.settings.setdefault('autoreload', True)
    self.settings.setdefault('compiled_template_cache', False)
    self.settings.setdefault('static_hash_cache', False)
    self.settings.setdefault('serve_traceback', True)

# Automatically reload modified modules
    if self.settings.get('autoreload'):
    from tornado import autoreload
    autoreload.start()

........

tornado中的web.py模块的一部分代码;

二,autoreload的实现原理是将各个文件的路径和文件的修改时间缓存起来;然后利用ioloop.py,定时得去check各个文件目前的修改时间和缓存中的时间是否一致,如果不一致,则加载;

def start(io_loop=None, check_time=500):
    """Begins watching source files for changes.

    .. versionchanged:: 4.1
    The ``io_loop`` argument is deprecated.
    """
    io_loop = io_loop or ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
        add_reload_hook(functools.partial(io_loop.close, all_fds=True))
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop)
    scheduler.start()

代码来自autoreload.py,  add_reload_hook是重加载时的回调函数;_reload_on_update 检查模块和模块的修改时间,并重新加载;

三,如果想让某个脚本启动autoreload模式,tornado提供了两种方式,一种是命令行运行,一种是讲autoreload的代码嵌入到脚本之中;

python -m tornado.autoreload path/to/script.py [args...]  或 python -m tornado.autoreload -m module.to.run [args...]

这种方式与在脚本中嵌入 autoreload.wait() 是一样的。

猜你喜欢

转载自blog.csdn.net/zzddada/article/details/113584236