当前位置: 首页>>代码示例>>Python>>正文


Python options.define函数代码示例

本文整理汇总了Python中tornado.options.options.define函数的典型用法代码示例。如果您正苦于以下问题:Python define函数的具体用法?Python define怎么用?Python define使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了define函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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


注:本文中的tornado.options.options.define函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。