文章来源:https://www.cnblogs.com/renfanzi/p/9585167.html
一、源码解读
tornado是facebook开源的非阻塞web容器,类似java的netty,tornado.options是负责解析tornado容器的全局参数的,同时也能够解析命令行传递的参数和从配置文件中解析参数。使用步骤如下:
from tornado.options import define, options
define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
help="Main user memcache servers")
def connect():
db = database.Connection(options.mysql_host)
...
Your ``main()`` method can parse the command line or parse a config file with
either::
tornado.options.parse_command_line()
# or
tornado.options.parse_config_file("/etc/server.conf")
命令行参数格式:–myoption=myvalue
配置文件可以是python文件,参数格式为:
myoption = "myvalue"
myotheroption = "myothervalue"
options = OptionParser()
"""Global options object.
All defined options are available as attributes on this object.
"""
def define(name, default=None, type=None, help=None, metavar=None,
multiple=False, group=None, callback=None):
"""Defines an option in the global namespace.
See `OptionParser.define`.
"""
return options.define(name, default=default, type=type, help=help,
metavar=metavar, multiple=multiple, group=group,
callback=callback)
def parse_command_line(args=None, final=True):
"""Parses global options from the command line.
See `OptionParser.parse_command_line`.
"""
return options.parse_command_line(args, final=final)
def parse_config_file(path, final=True):
"""Parses global options from a config file.
See `OptionParser.parse_config_file`.
"""
return options.parse_config_file(path, final=final)
二、应用
# 在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()
使用参数
使用options获取刚设置的参数
from tornado.options import options
....
application.listen(options.port)
.....
settings = {
'debug': options.debug,
}
完整代码
#!/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
示例二
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from test import aa
define('config', default=None, help='tornado settings file', type=str)
options.parse_command_line()
if options.config:
# print(options.settings)
aa()
else:
raise Exception("You must add a xxx.py at settings/ folder, then run: 'python app.py --settings=user'")
class IndexHandler(tornado.web.RequestHandler):
def get(self):
greeting = self.get_argument('greeting', 'Hello')
self.write(greeting + ', friendly user!')
if __name__ == "__main__":
app = tornado.web.Application(
handlers=[(r"/", IndexHandler)]
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(8000)
tornado.ioloop.IOLoop.current().start()
from tornado.options import options
import importlib
# db_config = importlib.import_module('settings.%s.db_config'%options.settings)
#
# options.config = {
# 'MONGO': db_config.MONGO,
# 'SETTINGS': {},
# }
def aa():
data = dict(options.items())
print("asdfasdf", data["config"])
一定要把options的东西放启动脚本的最上面, 要不下面调用的时候报错
问题出在哪呢?
多进程是启动多个,当已经define定义key的时候, OK, 可是同时启动多个啊, memory中已经有定义好的define的你定义的key了呀