#Tornado 使用手冊(一)---------- 簡單的tornado配置python
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 參數配置web
settings = { 'debug': True, # 開發模式 'gzip': True, # 支持gzip壓縮 'autoescape': None, 'xsrf_cookies': False, 'cookie_secret': 'xxx' } application = tornado.web.Application([ (r'/', MainHandler) ], **settings)
##3. 默認參數配置vim
# 在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. 使用參數cookie
使用options獲取剛設置的參數 from tornado.options import options .... application.listen(options.port) ..... settings = { 'debug': options.debug, }
##5. 完整代碼app
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: __author__ = 'okker.ma@gmail.com' 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()
運行:tornado
python web.py --port=9002 --debug=True