Tornado 使用手册(一)---------- 简单的tornado配置

Tornado 使用手册(一)———- 简单的tornado配置

1. 简单的web.py

        import tornado.ioloop
        import tornado.web

        import os
        from tornado.options import options, define
        class MainHandler(tornado.web.RequestHandler):

        def get(self):
            self.write("hello,world")


        settings = {
            'debug': True,
            'gzip': True,
            'autoescape': None,
            'xsrf_cookies': False,
            'cookie_secret': 'xxxx'
        }

    application = tornado.web.Application([
        (r'/', MainHandler)
    ])

    if __name__ == '__main__':
        application.listen(9002)
        tornado.ioloop.IOLoop.instance().start()

2. debug 参数配置

    settings = {
        'debug': True, # 开发模式
        'gzip': True, # 支持gzip压缩
        'autoescape': None,
        'xsrf_cookies': False,
        'cookie_secret': 'xxx'
    }

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

3. 默认参数配置

    # 在tornado.options.options配置变量名
    from tornado.options import define, options
    define('debug', default=True, help='enable debug mode')
    define('project_path', default=sys.path[0], help='deploy_path')
    define('port', default=8888, help='run on this port', type=int)
    # 从命令行中解析参数信息, 如 python web.py --port=9002, 这里的port解析
    tornado.options.parse_command_line()

4. 使用参数

使用options获取刚设置的参数

    from tornado.options import options
    ....
    application.listen(options.port)
    .....
    settings = {
        'debug': options.debug,
        }

5. 完整代码

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
    __author__ = '[email protected]'

    import tornado.ioloop
    import tornado.web

    import os
    from tornado.options import options, define

    #在options中设置几个变量
    define('debug', default=True, help='enable debug mode')
    define('port', default=9002, help='run on this port', type=int)

    # 解析命令行, 有了这行,还可以看到日志...
    tornado.options.parse_command_line()

    class MainHandler(tornado.web.RequestHandler):

        def get(self):
            self.write("hello,a world")

    settings = {
                'debug': options.debug,
                'gzip': True,
                'autoescape': None,
                'xsrf_cookies': False,
                'cookie_secret': 'xxxxxxx'
            }

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

    if __name__ == '__main__':
        application.listen(options.port)
        tornado.ioloop.IOLoop.instance().start()

运行:

    python web.py --port=9002 --debug=True

你可能感兴趣的:(Tornado 使用手册(一)---------- 简单的tornado配置)