Python tornado.options() Examples

The following are 21 code examples of tornado.options(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado , or try the search function .
Example #1
Source File: options.py    From dokomoforms with GNU General Public License v3.0 6 votes vote down vote up
def inject_options(**kwargs):
    """Add extra options programmatically.

    dokomoforms.options.parse_options reads from sys.argv if
    dokomoforms.options._arg is None. Calling
    dokomoforms.options.inject_options(name1='value1', name2='value2', ...) at
    the top of a file injects the given options instead.

    :param kwargs: name='value' arguments like the ones that would be passed
                   to webapp.py as --name=value or set in local_config.py as
                   name = 'value'
    """
    global _arg
    # The first element doesn't get read by tornado.options.parse_command_line,
    # so we might as well set it to None
    new_arg = [None]
    new_arg.extend(
        '--{name}={value}'.format(name=k, value=kwargs[k]) for k in kwargs
    )
    _arg = new_arg 
Example #2
Source File: init.py    From RobotAIEngine with Apache License 2.0 6 votes vote down vote up
def main():
    ''' main 函数
    '''
    # 开启 search_engin_server
    ioloop = tornado.ioloop.IOLoop.instance()
    server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    server.listen(options.port)

    def sig_handler(sig, _):
        ''' 信号接收函数
        '''
        logging.warn("Caught signal: %s", sig)
        shutdown(ioloop, server)

    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)
    ioloop.start() 
Example #3
Source File: webserver.py    From QUANTAXIS_RealtimeCollector with MIT License 6 votes vote down vote up
def main():
    asyncio.set_event_loop(asyncio.new_event_loop())
    define("port", default=8011, type=int, help="服务器监听端口号")

    define("address", default='0.0.0.0', type=str, help='服务器地址')
    define("content", default=[], type=str, multiple=True, help="控制台输出内容")
    parse_command_line()
    apps = Application(
        handlers=handlers,
        debug=True,
        autoreload=True,
        compress_response=True
    )
    port = options.port

    # stock_coll = QARTC_Stock(username='quantaxis', password='quantaxis')

    # threading.Thread(target=)

    http_server = tornado.httpserver.HTTPServer(apps)
    http_server.bind(port=options.port, address=options.address)
    """增加了对于非windows下的机器多进程的支持
    """
    http_server.start(1)
    tornado.ioloop.IOLoop.current().start() 
Example #4
Source File: helpers.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_command_line(extra_args_func=None):
    """Parse command line arguments for any Pyaiot application."""
    if not hasattr(options, "config"):
        define("config", default=None, help="Config file")
    if not hasattr(options, "broker_host"):
        define("broker_host", default="localhost", help="Broker host")
    if not hasattr(options, "broker_port"):
        define("broker_port", default=8000, help="Broker websocket port")
    if not hasattr(options, "debug"):
        define("debug", default=False, help="Enable debug mode.")
    if not hasattr(options, "key_file"):
        define("key_file", default=DEFAULT_KEY_FILENAME,
               help="Secret and private keys filename.")
    if extra_args_func is not None:
        extra_args_func()

    options.parse_command_line()
    if options.config:
        options.parse_config_file(options.config)
    # Parse the command line a second time to override config file options
    options.parse_command_line() 
Example #5
Source File: dashboard.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        self._nodes = {}
        if options.debug:
            logger.setLevel(logging.DEBUG)

        handlers = [
            (r'/', DashboardHandler),
        ]
        settings = {'debug': True,
                    "cookie_secret": "MY_COOKIE_ID",
                    "xsrf_cookies": False,
                    'static_path': options.static_path,
                    'template_path': options.static_path
                    }
        super().__init__(handlers, **settings)
        logger.info('Application started, listening on port {0}'
                    .format(options.web_port)) 
Example #6
Source File: pywebproxy.py    From MobileSF with GNU General Public License v3.0 6 votes vote down vote up
def startTornado(IP,PORT,log):
    try:
        server.bind(int(PORT), address=IP)
        # Useful for using custom loggers because of relative paths in secure requests
        # http://www.joet3ch.com/blog/2011/09/08/alternative-tornado-logging/
        server.start(int(1))
    except:
        print "\n[INFO] WebProxy Socket is already in use"
        pass
    #Clean Up
    rmfiles = [os.path.join(log,"requestdb"),os.path.join(log,"urls"),os.path.join(log,"WebTraffic.txt")]
    for fil in rmfiles:
        if os.path.exists(fil):
            os.remove(fil)
    logp = os.path.join(settings.LOG_DIR, 'webproxy.log')
    tornado.options.parse_command_line(args=["dummy_arg","--log_file_prefix="+logp,"--logging=info"])
    tornado.ioloop.PeriodicCallback(try_exit, 100).start()
    tornado.ioloop.IOLoop.instance().start() 
Example #7
Source File: websocket_manager.py    From ParlAI with MIT License 6 votes vote down vote up
def _make_app(self):
        """
        Starts the tornado application.
        """
        message_callback = self._on_new_message

        options['log_to_stderr'] = True
        tornado.options.parse_command_line([])

        return tornado.web.Application(
            [
                (
                    r"/websocket",
                    MessageSocketHandler,
                    {'subs': self.subs, 'message_callback': message_callback},
                )
            ],
            debug=self.debug,
        ) 
Example #8
Source File: websocket_manager.py    From ParlAI with MIT License 6 votes vote down vote up
def __init__(self, opt):
        """
        Create a WebsocketManager using the given setup options.
        """
        super().__init__(opt)
        self.opt = opt
        self.port = opt.get('port')
        self.subs = {}

        self.app = None
        self.debug = opt.get('is_debug', False)

        self.message_sender = WebsocketManager.MessageSender()

        self.service_reference_id = None

        self._parse_config(opt)
        self._complete_setup() 
Example #9
Source File: app.py    From tornado-shortener with MIT License 6 votes vote down vote up
def main():
    """
    Main function to start the webserver application and listen on the specified port.
    """
    tornado.options.parse_command_line()
    application = Application(tornado.options.options.domain,
                              tornado.options.options.salt,
                              tornado.options.options.redis_namespace,
                              tornado.options.options.redis_host,
                              int(tornado.options.options.redis_port),
                              tornado.options.options.redis_db,
                              tornado.options.options.redis_password,
                              int(tornado.options.options.ttl))
    if tornado.options.options.localhostonly:
        address = '127.0.0.1'
        logging.info('Listening to localhost only')
    else:
        address = ''
        logging.info('Listening to all addresses on all interfaces')
    application.listen(tornado.options.options.port, address=address, xheaders=True)
    tornado.ioloop.IOLoop.instance().start()


# Run main method if script is run from command line. 
Example #10
Source File: example_webserver.py    From PyZwaver with GNU General Public License v3.0 6 votes vote down vote up
def get(self, *path):
        token = path[0].split("/")
        logging.warning("DISPLAY ACTION> %s", token)
        try:
            tag = token[0]
            if tag == "ONE_NODE":
                tag += ":" + token[1]
            out = GetUpdate(token)
            SendToSocketJson(tag + ":", out)
        except Exception as e:
            logging.error("cannot processed: %s", path[0])
            print("-" * 60)
            traceback.print_exc(file=sys.stdout)
            print("-" * 60)
        self.finish()


# use --logging=none
# to disable the tornado logging overrides caused by
# tornado.options.parse_command_line( 
Example #11
Source File: main.py    From botbuilder-python with MIT License 5 votes vote down vote up
def run():
    """Main entry point for model runtime api."""

    # Register signal handlers.
    logging.info("Preparing signal handlers..")
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    # Set up model cache.
    # If containerizing, suggest initializing the directories (and associated
    # file downloads) be performed during container build time.
    logging.info("Initializing model directories:")
    logging.info("    bert  : %s", options.bert_model_dir)
    logging.info("    bidaf : %s", options.bidaf_model_dir)

    language_helper = LanguageHelper()
    if (
        language_helper.initialize_models(
            options.bert_model_dir, options.bidaf_model_dir
        )
        is False
    ):
        logging.error("Could not initilize model directories.  Exiting..")
        return

    # Build the configuration
    logging.info("Building config..")
    ref_obj = {"language_helper": language_helper}
    app_config = ModelHandler.build_config(ref_obj)

    logging.info("Starting Tornado model runtime service..")
    application = tornado.web.Application(app_config)
    application.listen(options.port)

    # Protect the loop with a try/catch
    try:
        # Start the app and wait for a close
        tornado.ioloop.IOLoop.instance().start()
    finally:
        # handle error with shutting down loop
        tornado.ioloop.IOLoop.instance().stop() 
Example #12
Source File: example_webserver.py    From PyZwaver with GNU General Public License v3.0 5 votes vote down vote up
def options(self):
        # no body
        self.set_status(204)
        self.finish() 
Example #13
Source File: helloworld.py    From honeything with GNU General Public License v3.0 4 votes vote down vote up
def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start() 
Example #14
Source File: pywebproxy.py    From MobileSF with GNU General Public License v3.0 4 votes vote down vote up
def options(self):
        return self.get() 
Example #15
Source File: options.py    From dokomoforms with GNU General Public License v3.0 4 votes vote down vote up
def parse_options():
    """tornado.options.parse_command_line doesn't cut it.

    Tells Tornado to read from the config.py file (which in turn reads from
    the local_config.py file), then from options specified by
    dokomoforms.options._arg (sys.argv if _arg is None, or the list of
    options in _arg otherwise).

    See dokomoforms.options.inject_options
    """
    tornado.options.parse_config_file(
        os.path.join(os.path.dirname(__file__), '..', 'config.py')
    )
    tornado.options.parse_command_line(_arg) 
Example #16
Source File: dashboard.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get(self, path=None):
        self.render("dashboard.html",
                    wsproto="wss" if options.broker_ssl else "ws",
                    wsserver="{}:{}".format(options.broker_host,
                                            options.broker_port),
                    camera_url=options.camera_url,
                    favicon=options.favicon,
                    logo_url=options.logo,
                    map_api_key=options.map_api_key,
                    title=options.title) 
Example #17
Source File: dashboard.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def extra_args():
    """Define extra command line arguments for dashboard application."""
    if not hasattr(options, "static_path"):
        define("static_path",
               default=os.path.join(os.path.dirname(__file__), "static"),
               help="Static files path (containing npm package.json file)")
    if not hasattr(options, "web_port"):
        define("web_port", default=8080,
               help="Web application HTTP port")
    if not hasattr(options, "broker_ssl"):
        define("broker_ssl", type=bool, default=False,
               help="Supply the broker websocket with ssl")
    if not hasattr(options, "camera_url"):
        define("camera_url", default=None,
               help="Default camera url")
    if not hasattr(options, "title"):
        define("title", default="IoT Dashboard",
               help="Dashboard title")
    if not hasattr(options, "logo"):
        define("logo", default=None,
               help="URL for a logo in the dashboard navbar")
    if not hasattr(options, "favicon"):
        define("favicon", default=None,
               help="Favicon url for your dashboard site")
    if not hasattr(options, "map_api_key"):
        define("map_api_key", default="", help="Google Maps API key") 
Example #18
Source File: dashboard.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(arguments=[]):
    """Start an instance of a dashboard."""
    if arguments != []:
        sys.argv[1:] = arguments

    try:
        parse_command_line(extra_args_func=extra_args)
    except SyntaxError as exc:
        logger.error("Invalid config file: {}".format(exc))
        return
    except FileNotFoundError as exc:
        logger.error("Config file not found: {}".format(exc))
        return

    start_application(Dashboard(), port=options.web_port) 
Example #19
Source File: app.py    From webspider with MIT License 4 votes vote down vote up
def main():
    define(name='port', default=8000, type=int, help='run on the given port')
    parse_command_line()
    logger.info('====== web server starting at http://0.0.0.0:{} ======'.format(options.port))
    if constants.DEBUG:
        logger.info('debug mode is enabled!!!')

    app = make_web_app()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    http_server.start()

    tornado.ioloop.IOLoop.instance().start() 
Example #20
Source File: init.py    From RobotAIEngine with Apache License 2.0 4 votes vote down vote up
def __init__(self):
        '''
        应用初始化
        '''
        settings = {
            'xsrf_cookies': False,
            'site_title': 'demo',
            'debug': options.debug,
            'static_path': os.path.join(options.project_path, 'static'),
            'template_path': os.path.join(options.project_path, 'tpl'),
        }
        handlers = auto_route_handlers
        logging.info("----> %s", handlers)
        tornado.web.Application.__init__(self, handlers, **settings) 
Example #21
Source File: example_webserver.py    From PyZwaver with GNU General Public License v3.0 3 votes vote down vote up
def main():
    global DRIVER, CONTROLLER, TRANSLATOR, NODESET, DB
    tornado.options.parse_command_line()
    # use --logging command line option to control verbosity
    # logging.basicConfig(level=logging.WARNING)
    logger = logging.getLogger()
    for h in logger.handlers:
        h.setFormatter(MyFormatter())

    # used to persist certain settings like node names
    logging.info("opening shelf: %s", OPTIONS.db)
    DB = Db(OPTIONS.db)

    application = tornado.web.Application(_HANDLERS, **_SETTINGS)

    logging.info("opening serial")
    device = MakeSerialDevice(OPTIONS.serial_port)

    DRIVER = Driver(device)
    CONTROLLER = Controller(
        DRIVER, pairing_timeout_secs=OPTIONS.pairing_timeout_secs)
    CONTROLLER.Initialize()
    CONTROLLER.WaitUntilInitialized()
    CONTROLLER.UpdateRoutingInfo()
    DRIVER.WaitUntilAllPreviousMessagesHaveBeenHandled()
    print(CONTROLLER)
    TRANSLATOR = CommandTranslator(DRIVER)
    NODESET = Nodeset(TRANSLATOR, CONTROLLER.GetNodeId())

    cp = CONTROLLER.props.product
    NODESET.put(
        CONTROLLER.GetNodeId(),
        time.time(),
        z.ManufacturerSpecific_Report,
        {'manufacturer': cp[0], 'type': cp[1], 'product': cp[2]})
    for n in CONTROLLER.nodes:
        TRANSLATOR.Ping(n, 3, False, "refresher")
    updater = NodeUpdater()
    TRANSLATOR.AddListener(updater)
    logging.warning("listening on port %d", OPTIONS.port)
    application.listen(OPTIONS.port)
    tornado.ioloop.PeriodicCallback(updater.Periodic, 2000).start()
    tornado.ioloop.IOLoop.instance().start()
    return 0