本文整理汇总了Python中tornado.options.options.define函数的典型用法代码示例。如果您正苦于以下问题:Python define函数的具体用法?Python define怎么用?Python define使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了define函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: define_logging_options
def define_logging_options(options=None):
"""Add logging-related flags to ``options``.
These options are present automatically on the default options instance;
this method is only necessary if you have created your own `.OptionParser`.
.. versionadded:: 4.2
This function existed in prior versions but was broken and undocumented until 4.2.
"""
if options is None:
# late import to prevent cycle
from tornado.options import options
options.define("logging", default="info",
help=("Set the Python log level. If 'none', tornado won't touch the "
"logging configuration."),
metavar="debug|info|warning|error|none")
options.define("log_to_stderr", type=bool, default=None,
help=("Send log output to stderr (colorized if possible). "
"By default use stderr if --log_file_prefix is not set and "
"no other logging is configured."))
options.define("log_file_prefix", type=str, default=None, metavar="PATH",
help=("Path prefix for log files. "
"Note that if you are running multiple tornado processes, "
"log_file_prefix must be different for each of them (e.g. "
"include the port number)"))
options.define("log_file_max_size", type=int, default=100 * 1000 * 1000,
help="max size of log files before rollover")
options.define("log_file_num_backups", type=int, default=10,
help="number of log files to keep")
options.add_parse_callback(lambda: enable_pretty_logging(options))
开发者ID:1-alex,项目名称:tornado,代码行数:31,代码来源:log.py
示例2: setup_settings
def setup_settings(settings_package, pull_options=True, default_settings='base', final=False):
from tornado.log import enable_pretty_logging
from tornado.options import options
options.define('settings', default=default_settings, help='Define settings module')
def parse_callback():
global settings
settings.load(settings_package, options.settings)
if pull_options:
# let's pull options from the settings and vice versa
for option_name in options:
src, dst = (settings, options) if option_name in settings else (options, settings)
setattr(dst, option_name, src[option_name])
# resets logging configuration
enable_pretty_logging()
options.add_parse_callback(callback=parse_callback)
global settings
settings.setup_settings = [settings_package, default_settings, final]
if final:
options.run_parse_callbacks()
开发者ID:miphreal,项目名称:tornado_conf,代码行数:25,代码来源:__init__.py
示例3: _add_debug
def _add_debug(logger):
"""Add a debug option to the option parser.
The debug option is True if --logging=DEBUG is passed, False otherwise.
"""
debug = logger.level == logging.DEBUG
options.define('debug', default=debug)
开发者ID:kadams54,项目名称:juju-gui-charm,代码行数:7,代码来源:manage.py
示例4: main
def main():
""" Starts a web service for handing datastore requests. """
global datastore_access
global server_node
global zookeeper
zookeeper_locations = appscale_info.get_zk_locations_string()
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--type', choices=dbconstants.VALID_DATASTORES,
default=dbconstants.VALID_DATASTORES[0],
help='Database type')
parser.add_argument('-p', '--port', type=int,
default=dbconstants.DEFAULT_PORT,
help='Datastore server port')
parser.add_argument('-v', '--verbose', action='store_true',
help='Output debug-level logging')
args = parser.parse_args()
if args.verbose:
logging.getLogger('appscale').setLevel(logging.DEBUG)
options.define('private_ip', appscale_info.get_private_ip())
options.define('port', args.port)
taskqueue_locations = get_load_balancer_ips()
server_node = '{}/{}:{}'.format(DATASTORE_SERVERS_NODE, options.private_ip,
options.port)
datastore_batch = DatastoreFactory.getDatastore(
args.type, log_level=logger.getEffectiveLevel())
zookeeper = zktransaction.ZKTransaction(
host=zookeeper_locations, db_access=datastore_batch,
log_level=logger.getEffectiveLevel())
zookeeper.handle.add_listener(zk_state_listener)
zookeeper.handle.ensure_path(DATASTORE_SERVERS_NODE)
# Since the client was started before adding the listener, make sure the
# server node gets created.
zk_state_listener(zookeeper.handle.state)
zookeeper.handle.ChildrenWatch(DATASTORE_SERVERS_NODE, update_servers_watch)
transaction_manager = TransactionManager(zookeeper.handle)
datastore_access = DatastoreDistributed(
datastore_batch, transaction_manager, zookeeper=zookeeper,
log_level=logger.getEffectiveLevel(),
taskqueue_locations=taskqueue_locations)
index_manager = IndexManager(zookeeper.handle, datastore_access,
perform_admin=True)
datastore_access.index_manager = index_manager
server = tornado.httpserver.HTTPServer(pb_application)
server.listen(args.port)
IOLoop.current().start()
开发者ID:AppScale,项目名称:appscale,代码行数:55,代码来源:datastore.py
示例5: getTornadoUrl
def getTornadoUrl():
import socket
from tornado.options import options
ip = socket.gethostbyname(socket.gethostname())
# Check config file
SERVER_CONFIG = '/etc/domoweb.cfg'
if not os.path.isfile(SERVER_CONFIG):
sys.stderr.write("Error: Can't find the file '%s'\n" % SERVER_CONFIG)
sys.exit(1)
options.define("port", default=40404, help="Launch on the given port", type=int)
options.parse_config_file(SERVER_CONFIG)
return "http://%s:%s/" % (ip, options.port)
开发者ID:ka2er,项目名称:domoweb,代码行数:14,代码来源:install.py
示例6: main
def main():
options.define("port", default="8888")
options.define("watch", type=str, multiple=True, default=".",
help="watch file or directory")
options.define("htdoc", type=str, default=".", help="root directory of HTML documents")
options.define("command", type=str, multiple=True, metavar="COMMAND",
help="run COMMAND when file or directory is changed")
options.parse_command_line()
mypath = os.path.dirname(os.path.abspath(__file__))
assets_path = os.path.join(mypath, 'assets')
for f in options.watch:
watcher.watch(f)
watcher.add_hook(_run_cmd)
watcher.start()
application = tornado.web.Application([
(r"/ws", WebSocketHandler),
(r"/assets/(.*)", tornado.web.StaticFileHandler, {"path": assets_path}),
(r"/(.*\.html)", MainHandler),
(r"/(.*)", tornado.web.StaticFileHandler, {"path": options.htdoc}),
])
application.listen(8888)
logging.info('starting application')
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
logging.info('bye')
开发者ID:zakkie,项目名称:sphinx-liveview,代码行数:31,代码来源:server.py
示例7: parse_config_file
def parse_config_file(filename):
"""Rewrite tornado default parse_config_file.
Parses and loads the Python config file at the given filename.
This version allow customize new options which are not defined before
from a configuration file.
"""
config = {}
exec(compile(io.open(filename, encoding="UTF-8").read().encode("UTF-8"), filename, "exec"), {}, config)
for name in config:
if name in options:
options[name] = config[name]
else:
options.define(name, config[name])
开发者ID:felinx,项目名称:djinn,代码行数:15,代码来源:options.py
示例8: make_app
def make_app(secret, is_autoscaler):
options.__dict__['_options'].clear()
options.define('secret', secret)
agent_factory = InfrastructureAgentFactory()
if is_autoscaler:
scaler_route = ('/instances', InstancesHandler,
{'agent_factory': agent_factory})
else:
scaler_route = ('/instances', Respond404Handler,
dict(reason='This node was not started as an autoscaler.'))
app = web.Application([
('/instance', InstanceHandler, {'agent_factory': agent_factory}),
scaler_route,
])
return app
开发者ID:AppScale,项目名称:appscale,代码行数:16,代码来源:__init__.py
示例9: start
def start(prefix, settings, modules, routes, known_exceptions, **kwargs):
"""starts the tornado application.
:param prefix: the url prefix
:param settings: the user defined settings
:param modules: the modules to load
:param handlers: the list of url routes (url, handler)
:param known_exceptions: the mapping of known exceptions to HTTP codes
:param kwargs: the tornado application arguments
"""
from tornado.options import options
options.define("config", type=str, help="path to config file",
callback=lambda p: options.parse_config_file(p, final=False))
options.define("port", default=8000, help="listening port", type=int)
options.define("address", default='127.0.0.1', help="listening address")
options.add_parse_callback(log.patch_logger)
loop = _get_event_loop()
modules_registry = ModulesRegistry(loop.asyncio_loop, log.gen_log)
for module in modules:
modules_registry.lazy_load(module, options)
for opt in settings:
options.define(**opt)
options.parse_command_line(final=True)
if not prefix.endswith('/'):
prefix += '/'
kwargs.update(options.group_dict('application'))
kwargs.setdefault('default_handler_class', handler.DefaultHandler)
# prevent override this option
kwargs['known_exceptions'] = known_exceptions
kwargs['modules'] = modules_registry
handlers = []
for uri, methods in routes:
log.app_log.info("add resource: %s", uri)
handlers.append((_concat_url(prefix, uri), compile_handler(methods)))
app = web.Application(handlers, **kwargs)
app.listen(options.port, options.address, xheaders=True)
signal.signal(signal.SIGTERM, lambda *x: loop.stop())
log.app_log.info("start listening on %s:%d", options.address, options.port or 80)
try:
loop.start()
except (KeyboardInterrupt, SystemExit):
pass
loop.close()
log.app_log.info("gracefully shutdown.")
开发者ID:pombredanne,项目名称:storm-2,代码行数:56,代码来源:application.py
示例10: main
def main():
options.define('certfile', help="Path to SSL certificate to enable TSL")
options.define('keyfile', help="Path to SSL key to enable TSL")
unparsed = options.parse_command_line()
if len(unparsed) == 1:
config_file = options.parse_command_line()[0]
else:
raise ValueError("Configuration file is not specified")
if options.certfile and options.keyfile:
ssl_options = {
"certfile": options.certfile,
"keyfile": options.keyfile,
}
else:
ssl_options = None
server = ForwardServer(ssl_options=ssl_options)
server.bind_from_config_file(config_file)
IOLoop.instance().start()
开发者ID:NetAngels,项目名称:forwarder,代码行数:18,代码来源:__main__.py
示例11: get
def get(self, path=None):
"""main page loader
if the path doesnt exists, it is set index
if path isnt toc, toc is loaded
if path isnt index, index is loaded
"""
page_content = ''
ajax = self.is_ajax()
data = False
theme = self.get_argument('theme', None)
if theme is not None:
options.define('theme', default=theme, mutable=True)
if path is None:
path = 'index'
if options.allow_data:
data = self.is_data()
path = slug_to_name(path)
if ajax is False or data is False:
if path is None or str(path).lower() != 'toc':
title, slug, date, template, content= self.parse_page('toc')
if path is None or str(path).lower() != 'index':
title, slug, date, template, content = self.parse_page('index')
title, slug, date, template, content = self.parse_page(path)
page_content += content
if ajax is True or data is True:
self.write({
'title': title,
'slug': slug,
'date': date,
'path': '/' + path,
'content': page_content
})
else:
page_template = self.get_template_page('base')
self.render(page_template, title=title, page_content=page_content)
开发者ID:blazejszczerba,项目名称:Cling,代码行数:44,代码来源:cling.py
示例12: main
def main():
""" Main. """
parser = argparse.ArgumentParser()
parser.add_argument(
'-v', '--verbose', action='store_true',
help='Output debug-level logging')
args = parser.parse_args()
logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
options.define('secret', appscale_info.get_secret())
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
my_ip = appscale_info.get_private_ip()
is_master = (my_ip == appscale_info.get_headnode_ip())
is_lb = (my_ip in appscale_info.get_load_balancer_ips())
is_tq = (my_ip in appscale_info.get_taskqueue_nodes())
is_db = (my_ip in appscale_info.get_db_ips())
if is_master:
global zk_client
zk_client = KazooClient(
hosts=','.join(appscale_info.get_zk_node_ips()),
connection_retry=ZK_PERSISTENT_RECONNECTS)
zk_client.start()
# Start watching profiling configs in ZooKeeper
stats_app.ProfilingManager(zk_client)
app = tornado.web.Application(
stats_app.get_local_stats_api_routes(is_lb, is_tq, is_db)
+ stats_app.get_cluster_stats_api_routes(is_master),
debug=False
)
app.listen(constants.HERMES_PORT)
# Start loop for accepting http requests.
IOLoop.instance().start()
logger.info("Hermes is up and listening on port: {}."
.format(constants.HERMES_PORT))
开发者ID:AppScale,项目名称:appscale,代码行数:44,代码来源:hermes_server.py
示例13: get
def get(self, path=None):
"""main page loader
if the path doesnt exists, it is set index
if path isnt toc, toc is loaded
if path isnt index, index is loaded
"""
page_content = ""
ajax = self.is_ajax()
data = False
preview = False
theme = self.get_argument("theme", None)
if theme is not None:
options.define("theme", default=theme, mutable=True)
if path is None:
path = "index"
if options.allow_data:
data = self.is_data()
if options.allow_preview:
preview = self.is_preview()
path = slug_to_name(path)
if ajax is False or data is False:
if path is None or str(path).lower() != "toc":
title, slug, date, template, content = self.parse_page("toc")
if path is None or str(path).lower() != "index":
title, slug, date, template, content = self.parse_page("index")
title, slug, date, template, content = self.parse_page(path, is_preview=preview)
page_content += content
if ajax is True or data is True:
self.write({"title": title, "slug": slug, "date": date, "path": "/" + path, "content": page_content})
else:
page_template = get_template_page("base")
self.render(page_template, title=title, page_content=page_content)
开发者ID:emehrkay,项目名称:Cling,代码行数:41,代码来源:cling.py
示例14: define_logging_options
def define_logging_options(options=None):
if options is None:
# late import to prevent cycle
from tornado.options import options
options.define(
"logging",
default="info",
help=("Set the Python log level. If 'none', tornado won't touch the " "logging configuration."),
metavar="debug|info|warning|error|none",
)
options.define(
"log_to_stderr",
type=bool,
default=None,
help=(
"Send log output to stderr (colorized if possible). "
"By default use stderr if --log_file_prefix is not set and "
"no other logging is configured."
),
)
options.define(
"log_file_prefix",
type=str,
default=None,
metavar="PATH",
help=(
"Path prefix for log files. "
"Note that if you are running multiple tornado processes, "
"log_file_prefix must be different for each of them (e.g. "
"include the port number)"
),
)
options.define(
"log_file_max_size", type=int, default=100 * 1000 * 1000, help="max size of log files before rollover"
)
options.define("log_file_num_backups", type=int, default=10, help="number of log files to keep")
options.add_parse_callback(enable_pretty_logging)
开发者ID:TongZen,项目名称:serholiu.com,代码行数:38,代码来源:log.py
示例15: SingleQueryHandler
import json
import motor
import tornado.ioloop
import tornado.web
import tornado.httpserver
from random import randint
from tornado.options import options
from commons import JsonHandler, JsonHelloWorldHandler, PlaintextHelloWorldHandler, HtmlHandler
from tornado.ioloop import IOLoop
IOLoop.configure('tornado.platform.asyncio.AsyncIOLoop')
options.define('port', default=8888, type=int, help="Server port")
options.define('mongo', default='localhost', type=str, help="MongoDB host")
options.define('backlog', default=8192, type=int, help="Server backlog")
class SingleQueryHandler(JsonHandler):
async def get(self):
world = await db.world.find_one(randint(1, 10000))
world = {self.ID: int(world['_id']),
self.RANDOM_NUMBER: int(world[self.RANDOM_NUMBER])
}
response = json.dumps(world)
self.finish(response)
开发者ID:Jesterovskiy,项目名称:FrameworkBenchmarks,代码行数:29,代码来源:server_py3.py
示例16: bootstrap
def bootstrap(config_file=None):
options.define('config', config_file or tinyurld.default_config, type=str, help='Config file path')
options.define('host', '0.0.0.0', type=str, help='Ip address for bind')
options.define('port', 8888, type=int, help='application port')
options.define('autoreload', False, type=bool,
help='Autoreload application after change files', group='application')
options.define('debug', False, type=bool, help='Debug mode', group='application')
options.define('mongo_host', type=str, help='MongoDB host IP', group='mongodb')
options.define('mongo_port', 27017, type=int, help='MongoDB port', group='mongodb')
options.define('mongo_user', None, type=str, help='MongoDB user', group='mongodb')
options.define('mongo_password', None, type=str, help='MongoDB user password', group='mongodb')
options.parse_command_line()
options.parse_config_file(options.config)
# override options from config file with command line args
options.parse_command_line()
tornado.log.app_log.info('Read config: {}'.format(options.config))
开发者ID:den-gts,项目名称:myTinyURl,代码行数:18,代码来源:app.py
示例17: import
from appscale.admin.instance_manager import (
instance_manager as instance_manager_module)
from appscale.admin.instance_manager import InstanceManager
from appscale.admin.instance_manager import instance
from appscale.admin.instance_manager import utils
from appscale.common import (
file_io,
appscale_info,
misc,
monit_interface,
testing
)
from appscale.common import monit_app_configuration
from appscale.common.monit_interface import MonitOperator
options.define('login_ip', '127.0.0.1')
options.define('syslog_server', '127.0.0.1')
if not hasattr(options, 'private_ip'):
options.define('private_ip', '<private_ip>')
options.define('db_proxy', '<private_ip>')
options.define('load_balancer_ip', '<private_ip>')
options.define('tq_proxy', '<private_ip>')
class TestInstanceManager(AsyncTestCase):
@gen_test
def test_start_app_goodconfig_python(self):
testing.disable_logging()
version_details = {'runtime': 'python27',
开发者ID:AppScale,项目名称:appscale,代码行数:31,代码来源:test_instance_manager.py
示例18: main
def main():
candidates = ["bootstrap.ini"]
if len(sys.argv) > 1:
candidates.append(sys.argv[1])
config = ConfigParser.SafeConfigParser()
config.read(candidates)
options.define("db_engine", config.get("database", "db_engine"))
options.define("db_echo", True)
from trade.models import engine, Currency, Instrument, User, Broker, DepositMethods
session = scoped_session(sessionmaker(bind=engine))
for section_name in config.sections():
if section_name == "currencies":
for id, currency_json in config.items(section_name):
c = json.loads(currency_json)
if Currency.get_currency(session, c[0]):
continue
e = Currency(
code=c[0],
sign=c[1],
description=c[2],
is_crypto=c[3],
pip=c[4],
format_python=c[5],
format_js=c[6],
human_format_python=c[7],
human_format_js=c[8],
)
session.add(e)
session.commit()
if section_name == "instruments":
for id, instrument_json in config.items(section_name):
currency_description = json.loads(instrument_json)
if Instrument.get_instrument(session, currency_description[0]):
continue
e = Instrument(
symbol=currency_description[0],
currency=currency_description[1],
description=currency_description[2],
)
session.add(e)
session.commit()
if section_name[:4] == "user":
if not User.get_user(session, config.get(section_name, "username")):
broker_id = None
broker_username = None
password = base64.b32encode(os.urandom(10))
transaction_fee_buy = None
transaction_fee_sell = None
verified = 0
is_system = False
is_staff = False
is_broker = False
state = None
try:
broker_id = config.getint(section_name, "broker_id")
except Exception, e:
pass
try:
broker_username = config.get(section_name, "broker_username")
except Exception, e:
pass
try:
password = config.get(section_name, "password")
except Exception, e:
pass
try:
transaction_fee_buy = config.getint(section_name, "transaction_fee_buy")
except Exception, e:
pass
开发者ID:bitbuyercho,项目名称:bitex,代码行数:83,代码来源:bootstrap.py
示例19: get_application
# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.web
from tornado.options import options
from logbook import RotatingFileHandler, info
from . import handler
from . import applicationconfig
options.define("proxy", type=bool, default=False, help="if proxy environment, indicate this option.")
def get_application():
return tornado.web.Application([(r"/(?P<service>.+)", handler.Proxy, dict(needProxy=options.proxy))])
def log_setup():
log = RotatingFileHandler(applicationconfig.LOG_PATH, max_size=104857600, backup_count=5)
log.push_application()
def start():
tornado.options.parse_command_line()
application = get_application()
application.listen(applicationconfig.PORT)
log_setup()
tornado.ioloop.IOLoop.current().start()
info("Proxy run on port:{0}", applicationconfig.PORT)
开发者ID:koyadouhu,项目名称:WebhookGather,代码行数:31,代码来源:server.py
示例20: load_app_settings
import motor
from os import path
from tornado.ioloop import IOLoop
from tornado.options import options
from requesthandlers.api import ApiHandler
from requesthandlers.api.player import PlayerHandler
from requesthandlers.api.user import UserHandler
from requesthandlers.api.tournament import TournamentHandler
from requesthandlers.api.section import SectionHandler
from requesthandlers.api.session import SessionHandler
from requesthandlers.api.lookups import LookupsHandler
from requesthandlers import IndexPageHandler, VerifyPageHandler
from app import CustomApp
options.define('port', default=8888, help='run on the given port', type=int)
def load_app_settings():
db = pymongo.MongoClient().chessrank
return db.settings.find_one()
def main():
server_path = path.dirname(__file__)
template_path = path.join(server_path, 'templates')
static_path = path.normpath(path.join(server_path, '..', 'client'))
settings = {
'static_path': static_path,
'template_path': template_path,
'xsrf_cookies': False, # TODO: Enable
'login_url': '/',
开发者ID:rmoritz,项目名称:chessrank,代码行数:31,代码来源:main.py
注:本文中的tornado.options.options.define函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论