def load_settings():
    '''
        Load settings from command line and config file.
    '''

    # Parse command line
    options.logging = 'none' # To turn off logging settings
    options.log_to_stderr = True # Log to stderr
    parse_command_line()

    # Load settings from another config file if given
    if options.config:
        parse_config_file(options.config + '.conf')

    # Log file prefix
    options.log_file_prefix = ''.join((
        'log/',
        options.name,
        '-',
        str(options.port),
        '.log',
    ))

    # Logging settings
    if options.logging == 'none': # There are no logging settings before
        options.logging = 'debug' if options.debug else 'info'
        enable_pretty_logging(options=options)

    pretty_options_output()
Beispiel #2
0
def parser():
    define('script', default='/var/maple/')
    define('dbhost', default='localhost')
    define('dbuser', default='root')
    define('dbpass', default='')
    define('db', default='maple')
    parse_config_file('/etc/maple/default.conf')
def main():
    """Entry point for bitsd."""
    enable_pretty_logging()

    try:
        parse_config_file('/etc/bitsd.conf')
    except IOError:
        LOG.warning('Config file not found, using defaults and command line.')

    try:
        parse_command_line()
    except tornado.options.Error as error:
        sys.stderr.write('{}\n'.format(error))
        sys.exit(0)

    persistence.start()
    server.start()
    listener.start()

    # Add signal handlers...
    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

    if not options.log_requests:
        logging.getLogger("tornado.access").setLevel(logging.WARNING)

    tornado.ioloop.IOLoop.instance().start()
Beispiel #4
0
def make_app():
  parse_config_file('./config.py')
  assert options.db_url, "Need a database URL"

  session_factory = make_session_factory(options.db_url)

  # group is named (?P<name>group)
  handlers = [
        url(r"/", MainHandler),
        url(r"/api/v1", InfoView, name='api'),
        url(r'/api/v1/assets', AssetListView),
        url(r'/api/v1/assets/(?P<asset_id>[0-9]+)', AssetView, name='asset'),
        url(r'/api/v1/layers', LayerListView),
        url(r'/api/v1/wells', WellListView),
        url(r'/api/v1/intersection', IntersectionListView),
    ]

  settings = {
    'session_factory': session_factory,
    'debug': options.debug,
    'template_path': './template/',
    'static_path': './static/',
    'static_url_prefix': '/static/'
  }
  
  return Application(handlers, **settings )
Beispiel #5
0
def main():
    parse_command_line()
    flagfile = os.path.join(os.path.dirname(__file__), options.flagfile)
    parse_config_file(flagfile)

    settings = dict(
        login_url='/todo/login',
        debug=True,
        template_path=os.path.join(os.path.dirname(__file__), 'templates'),
        static_path=os.path.join(os.path.dirname(__file__), 'static'),

        cookie_secret=options.cookie_secret,
        dropbox_consumer_key=options.dropbox_consumer_key,
        dropbox_consumer_secret=options.dropbox_consumer_secret,
        )
    #print options.dropbox_consumer_key
    #print options.dropbox_consumer_secret
    app = Application([
            ('/', RootHandler),
            ('/todo/?', TodoHandler),
            ('/todo/add', AddHandler),
            ('/delete', DeleteHandler),
            ('/create', CreateHandler),
            ('/todo/login', DropboxLoginHandler),
            ('/todo/logout', LogoutHandler),
            ], **settings)
    app.listen(options.port,address='127.0.0.1',xheaders=True)
    IOLoop.instance().start()
    def run(self):
        from tornado import options
                
        control = Control(file_archive='',db_url=self.db_url)
        #control.api_logon(self.ims_user, self.password)
        
        #The config file is reloaded here, as some of the logging options could have been reset
        #when the feeds and filters were loaded
        if os.path.isfile(self.config_file):
            logging.debug("Loading options from: %s" % self.config_file)        
            options.parse_config_file(self.config_file, final=False)
        else:
            logging.warning("The config file was not loaded: %s" % self.config_file)
        

        path, name = os.path.split(self.path)
        for prefix, funcname in self.cash_map.iteritems():
            if name.lower().startswith(prefix.lower()):
                func = getattr(control, funcname)
                break
        else:
            msg = "Unknown file name [%s]" % name
            raise ValueError(msg)
        
        func(self.path,self.ims_user, self.recipents)
        
        
    
        
def make_server(config_path):
    root = path.dirname(__file__)
    static_path = path.join(root, 'static')
    template_path = path.join(root, 'template')

    define('port', default=7777, type=int)
    define('production', default=False, type=bool)
    define('mongo_db_name', default='open_wireless_map', type=str)
    define('mongo_host', default='localhost', type=str)
    define('mongo_port', default=27017, type=int)
    define('mongo_user', default=None, type=str)
    define('mongo_password', default=None, type=str)
    define('api_password_hash', default=None, type=str)

    parse_config_file(config_path)

    app_config = dict(static_path=static_path,
                      template_path=template_path)
    if not options.production:
        app_config.update(debug=True)

    server = Application(url_map, **app_config)
    server.settings['api_password_hash'] = options.api_password_hash
    server.settings['mongo'] = get_mongo(db_name=options.mongo_db_name,
                                         host=options.mongo_host,
                                         port=options.mongo_port,
                                         user=options.mongo_user,
                                         password=options.mongo_password)
    return server
Beispiel #8
0
    def run_from_argv(self, prog_name, argv=None, **_kwargs):
        app_settings = settings.APP_SETTINGS
        argv = list(filter(self.flower_option, argv))
        # parse the command line to get --conf option
        parse_command_line([prog_name] + argv)
        try:
            parse_config_file(options.conf, final=False)
            parse_command_line([prog_name] + argv)
        except IOError:
            if options.conf != settings.CONFIG_FILE:
                raise

        app_settings["debug"] = options.debug
        if options.cookie_secret:
            app_settings["cookie_secret"] = options.cookie_secret

        if options.url_prefix:
            prefix = options.url_prefix.strip("/")
            app_settings["static_url_prefix"] = "/{0}/static/".format(prefix)
            app_settings["login_url"] = "/{0}/login".format(prefix)
            settings.URL_PREFIX = prefix
        settings.CELERY_INSPECT_TIMEOUT = options.inspect_timeout
        settings.AUTO_REFRESH = options.auto_refresh

        if options.debug and options.logging == "info":
            options.logging = "debug"
            enable_pretty_logging()

        if options.auth:
            app_settings[GoogleOAuth2Mixin._OAUTH_SETTINGS_KEY] = {
                "key": options.oauth2_key or os.environ.get("GOOGLE_OAUTH2_KEY"),
                "secret": options.oauth2_secret or os.environ.get("GOOGLE_OAUTH2_SECRET"),
                "redirect_uri": options.oauth2_redirect_uri or os.environ.get("GOOGLE_OAUTH2_REDIRECT_URI"),
            }

        # Monkey-patch to support Celery 2.5.5
        self.app.connection = self.app.broker_connection

        self.app.loader.import_default_modules()
        flower = Flower(celery_app=self.app, options=options, **app_settings)
        atexit.register(flower.stop)

        # graceful shutdown on SIGTERM
        def signal_handler(signal, frame):
            logger.info("SIGTERM detected, shutting down")
            sys.exit(0)

        signal.signal(signal.SIGTERM, signal_handler)

        logger.info(
            "Visit me at http%s://%s:%s", "s" if flower.ssl else "", options.address or "localhost", options.port
        )
        logger.info("Broker: %s", self.app.connection().as_uri())
        logger.debug("Registered tasks: \n%s", pformat(sorted(self.app.tasks.keys())))
        logger.debug("Settings: %s", pformat(app_settings))

        try:
            flower.start()
        except (KeyboardInterrupt, SystemExit):
            pass
Beispiel #9
0
def main():
    if os.path.exists(options.config_file):
        parse_config_file(options.config_file)
    parse_command_line()

    app = Application(
        [
            url(r'/token/?', auth.TokenHandler),
            url(r'/tasks/?', tasks.TaskHandler),
            url(r'/tasks/({uuid})/?'.format(uuid=UUID_PATTERN),
                tasks.TaskHandler),
            url(r'/domains/?', vms.DomainHandler),
            url(r'/domains/({uuid})/?'.format(uuid=UUID_PATTERN),
                vms.DomainHandler),
            url(r'/nodes/?', vms.NodeHandler),
            url(r'/nodes/([\d+])/?', vms.NodeHandler)
        ],
        template_path=os.path.join(BASE_DIR, 'templates'),
        static_path=os.path.join(BASE_DIR, 'static'),
        **options.group_dict('application')
    )
    app.listen(options.port)

    logging.info('Listening on http://localhost:%d' % options.port)

    IOLoop.current().add_callback(start_queue, app)
    IOLoop.current().start()
Beispiel #10
0
def main():
    global http_server

    try:
        signal(SIGTERM, on_signal)

        parse_command_line()
        if options.config != None:
            parse_config_file(options.config)

        path = join(dirname(__file__), "templates")

        application = Application(
            [(r"/", IndexHandler), (r"/stock", StockHandler)],
            template_path=path,
            static_path=join(dirname(__file__), "static"),
        )

        application.db = motor.MotorClient(options.db_host, options.db_port).open_sync()[options.db_name]

        http_server = HTTPServer(application)
        http_server.listen(options.port, options.address)
        log().info("server listening on port %s:%d" % (options.address, options.port))
        if log().isEnabledFor(DEBUG):
            log().debug("autoreload enabled")
            tornado.autoreload.start()
        IOLoop.instance().start()

    except KeyboardInterrupt:
        log().info("exiting...")

    except BaseException as ex:
        log().error("exiting due: [%s][%s]" % (str(ex), str(format_exc().splitlines())))
        exit(1)
Beispiel #11
0
def load_config(path=None):
    '''
        This extends the tornado parser to enable use in
        heroku where options are accessed through os.getenv

        Will read file at path if exists

        Will then read environment variables to override

        Will then parse command line to override

    '''
    if path is not None and os.path.isfile(path):
        logging.info("loading config from %s", path)
        parse_config_file(path)

    for k in options.as_dict():
        ''' danger: access of private variables '''
        value = os.getenv(k)
        if value:
            name = options._normalize_name(k)
            option = options._options.get(name)
            option.parse(value)

    parse_command_line()
Beispiel #12
0
def parse_configs(config_files):
    """Reads command line options / config file and bootstraps logging.
    """

    parse_command_line(final=False)

    if options.config:
        configs_to_read = options.config
    else:
        configs_to_read = config_files

    configs_to_read = filter(
        None, [configs_to_read] if not isinstance(configs_to_read, (list, tuple)) else configs_to_read
    )

    for config in configs_to_read:
        parse_config_file(config, final=False)

    # override options from config with command line options
    parse_command_line(final=False)

    bootstrap_core_logging()

    for config in configs_to_read:
        log.debug('using config: %s', config)
        if options.autoreload:
            tornado.autoreload.watch(config)
Beispiel #13
0
def main():
    # We have settings?
    if os.path.exists('settings.py'):
        parse_config_file('settings.py')
    # What about command line args?
    parse_command_line()
    ssl_options = {}
    # Check SSL options
    if (options.certfile and options.keyfile) and (os.path.exists(
            os.path.abspath(options.certfile)) and os.path.exists(
            os.path.abspath(options.keyfile))):
        ssl_options['certfile'] = os.path.abspath(options.certfile)
        ssl_options['keyfile'] = os.path.abspath(options.keyfile)
    server = HTTPServer(app(), ssl_options=ssl_options or None)
    if options.debug:
        options.address = '127.0.0.1'
        log.debug('Run application in debug mode on %s:%s.' % (options.address,
                                                               options.port))
        server.listen(options.port, options.address)
    else:
        log.debug('Run application in normal mode on %s:%s.' % (options.address,
                                                                options.port))
        server.bind(options.port, options.address)
        server.start(0)
    IOLoop.instance().start()
Beispiel #14
0
    def __init__(self):
        define("xmpp_jid", help="XMPP JID. e.g.: [email protected]", type=str)
        define("xmpp_password", help="XMPP Password.", type=str)
        define("xmpp_host", help="XMPP Host", type=str)
        define("xmpp_port", help="XMPP Port", type=int)
        define("xmpp_relay_user", help="XMPP relay user", type=str)
        define("callback_port", help="HTTP callback port.", default=15827, type=int)

        config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "upstream-config.py")
        parse_config_file(config_path)

        self.relay_user = options["xmpp_relay_user"].value()

        super(XMPPManager, self).__init__("XMPPManager(%s)", options["xmpp_jid"].value())

        start = "http://127.0.0.1:%d/start/" % options["callback_port"].value()
        message = "http://127.0.0.1:%d/message/" % options["callback_port"].value()
        self.xmpp = XMPPProxyBot(options["xmpp_jid"].value(), options["xmpp_password"].value(), start, message)

        self.app = tornado.web.Application(
            [
                (r"/start/", XMPPProxyCallback, {"callback": self.on_start}),
                (r"/message/", XMPPProxyCallback, {"callback": self.on_message}),
            ]
        )

        if self.xmpp.connect((options["xmpp_host"].value(), options["xmpp_port"].value())):
            self.xmpp.process(block=False)

        self.streams = {}
        self.app.listen(options["callback_port"].value())
Beispiel #15
0
    def run_from_argv(self, prog_name, argv=None, **_kwargs):
        app_settings = settings.APP_SETTINGS
        argv = list(filter(self.flower_option, argv))
        # parse the command line to get --conf option
        parse_command_line([prog_name] + argv)
        try:
            parse_config_file(options.conf, final=False)
            parse_command_line([prog_name] + argv)
        except IOError:
            if options.conf != settings.CONFIG_FILE:
                raise

        app_settings['debug'] = options.debug
        if options.cookie_secret:
            app_settings['cookie_secret'] = options.cookie_secret

        if options.url_prefix:
            logger.error('url_prefix option is not supported anymore')

        settings.AUTO_REFRESH = options.auto_refresh

        if options.debug and options.logging == 'info':
            options.logging = 'debug'
            enable_pretty_logging()

        if options.auth:
            app_settings[GoogleOAuth2Mixin._OAUTH_SETTINGS_KEY] = {
              'key': options.oauth2_key or os.environ.get('GOOGLE_OAUTH2_KEY'),
              'secret': options.oauth2_secret or os.environ.get('GOOGLE_OAUTH2_SECRET'),
              'redirect_uri': options.oauth2_redirect_uri or os.environ.get('GOOGLE_OAUTH2_REDIRECT_URI'),
            }

        # Monkey-patch to support Celery 2.5.5
        self.app.connection = self.app.broker_connection

        self.app.loader.import_default_modules()
        flower = Flower(celery_app=self.app, options=options,
                        **app_settings)
        atexit.register(flower.stop)

        # graceful shutdown on SIGTERM
        def signal_handler(signal, frame):
            logger.info('SIGTERM detected, shutting down')
            sys.exit(0)
        signal.signal(signal.SIGTERM, signal_handler)

        logger.info('Visit me at http%s://%s:%s',
                    's' if flower.ssl else '',
                    options.address or 'localhost',
                    options.port)
        logger.info('Broker: %s', self.app.connection().as_uri())
        logger.debug('Registered tasks: \n%s',
                     pformat(sorted(self.app.tasks.keys())))
        logger.debug('Settings: %s', pformat(app_settings))

        try:
            flower.start()
        except (KeyboardInterrupt, SystemExit):
            pass
def main():
    define("port", default=8888, type=int)
    define("db", default=":memory:")
    define("db_echo", default=True)
    parse_config_file("application.cfg")
    logging.info("Starting tornado server")
    Server.get_app().listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
Beispiel #17
0
def main():
    init_config()
    options.parse_config_file("/var/www/app/webssh.conf")

    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    IOLoop.instance().start()
    tornado.ioloop.IOLoop.instance().start()
def config():
    define('CACHE_TIME', default=5 * 60, help="The cached time for every news, in seconds")
    define('DEBUG', default=True, help="The global debug control")
    define("PORT", default=8000, help="PORT")

    if os.path.exists('config.py'):
        parse_config_file('config.py')
    options.log_to_stderr = False
Beispiel #19
0
def parse_file(filepath):
    try:
        parse_config_file(filepath)
    except IOError as e:
        pass
    except Error as e:
        print("Error parsing config file %s:" % filepath)
        print("\t%s" % e)
        sys.exit(-1)
Beispiel #20
0
def main(config_file="./kew_pe.conf"):    
    ''' parse the command line - new up the appl and listen on port '''
    if os.path.isfile(config_file):
        print("Loading config file %s" % os.path.abspath(config_file))
        options.parse_config_file(config_file)
    options.parse_command_line()
    
    logging.basicConfig(level=logging.DEBUG, format="[%(levelname)1.1s %(asctime)s %(process)d %(module)s:%(lineno)d] %(message)s")
    run()
Beispiel #21
0
def main(config_file="./kew_register.conf"):
            
    ''' parse the command line - new up the appl and listen on port '''
    if os.path.isfile(config_file):
        print ("Loading configuration file %s" % config_file)
        options.parse_config_file(config_file)
    options.parse_command_line()
    
    run('localhost', options.options.db_url)
Beispiel #22
0
def make_app(environ, argv1=None):
    parser = OptionParser()
    parser.add_option(
        "-c", "--config", dest="config_file", 
        help="Configuration file", metavar="FILE")
    parser.add_option(
        "-d", "--data", dest="data",
        help="Data directory", metavar="FILE")
    parser.add_option(
        "-l", "--logfile", dest="log_file_prefix",
        help="Log file", metavar="FILE")
    parser.add_option(
        "-L", "--log-level", dest="logging",
        help="Log level", metavar="info|warning|error|none")
    parser.add_option(
        "-p", "--port", dest="port",
        help="Port", default="0")

    opts, args = parser.parse_args(argv1)
    name = args[0]
    
    if opts.data.startswith('/'):
        instance_path = os.path.join(opts.data, name)
    else:
        instance_path = os.path.join(os.getcwd(), opts.data, name) 
    config_file = opts.config_file or os.path.join(os.path.abspath(instance_path), "etc", "vaytrou.conf")
    if config_file is not None:
        parse_config_file(config_file)    
    parse_command_line([])

    # Load command line options over Tornado options
    for k, v in options.items():
        optv = getattr(opts, k, None)
        if optv is not None:
            try:
                options[k].set(v.type(optv))
            except:
                import pdb; pdb.set_trace()
                raise

    finder = PersistentApplicationFinder(
        'file://%s/%s/var/Data.fs' % (options.data, name), appmaker)
    index = finder(environ)
    index.fwd = Rtree('%s/%s/var/vrt1' % (options.data, name))
    setattr(index, 'name', name)
    setattr(index, 'data', options.data)

    return Application(index, [
        (r'/', MainHandler),
        (r'/intersection/?', IntersectionHandler),
        (r'/nearest/?', NearestHandler),
        (r'/distance/?', DistanceHandler),
        (r'/within/?', WithinHandler),
        (r'/item/([-\w]+);([-0-9\.]+),([-0-9\.]+),([-0-9\.]+),([-0-9\.]+)', 
         SingleItemHandler),
        (r'/items/([-\w]+)', MultipleItemsHandler)
        ])
Beispiel #23
0
    def run_from_argv(self, prog_name, argv=None, **_kwargs):
        app_settings = settings.APP_SETTINGS
        argv = list(filter(self.flower_option, argv))
        try:
            parse_config_file('flowerconfig.py', final=False)
            print("Parsed Flower configfile")
        except IOError:
            print("Flower configfile not found")
            pass
        parse_command_line([prog_name] + argv)

        app_settings['debug'] = options.debug
        if options.cookie_secret:
            app_settings['cookie_secret'] = options.cookie_secret

        if options.url_prefix:
            prefix = options.url_prefix.strip('/')
            app_settings['static_url_prefix'] = '/{0}/static/'.format(prefix)
            app_settings['login_url'] = '/{0}/login'.format(prefix)
            settings.URL_PREFIX = prefix
        settings.CELERY_INSPECT_TIMEOUT = options.inspect_timeout
        settings.AUTO_REFRESH = options.auto_refresh


        if options.debug:
            logging.getLogger().setLevel(logging.DEBUG)

        #set the celery BROKER_URL based on the config broker value
        self.app.conf['BROKER_URL'] = options.broker
        #overwrite if environment variables REDIS_HOST, REDIS_PORT, REDIS_DB are set
        if os.environ.get('REDIS_HOST') and os.environ.get('REDIS_PORT')  and os.environ.get('REDIS_DB'):
            self.app.conf['BROKER_URL'] = "redis://" + str(os.environ.get('REDIS_HOST')) + ":" + str(os.environ.get('REDIS_PORT')) + "/" + str(os.environ.get('REDIS_DB'))
        # Monkey-patch to support Celery 2.5.5
        #self.app.connection = self.app.broker_connection
        flower = Flower(celery_app=self.app, options=options,
                        **app_settings)
        atexit.register(flower.stop)

        # graceful shutdown on SIGTERM
        def signal_handler(signal, frame):
            logging.info('SIGTERM detected, shutting down')
            sys.exit(0)
        signal.signal(signal.SIGTERM, signal_handler)

        logging.info('Visit me at http%s://%s:%s',
                     's' if flower.ssl else '',
                     options.address or 'localhost',
                     options.port)
        logging.info('My Broker: %s', self.app.connection().as_uri())
        logging.debug('Registered tasks: \n%s',
                      pformat(sorted(self.app.tasks.keys())))
        logging.debug('Settings: %s', pformat(app_settings))

        try:
            flower.start()
        except (KeyboardInterrupt, SystemExit):
            pass
Beispiel #24
0
def main():
    config_path = "simple.conf"
    if os.path.isfile(config_path):     
        logging.info("loading config file")       
        parse_config_file(config_path)
    
    parse_command_line()

    s3_config = AWSConfig(options.aws_access_key_id,
                          os.environ.get("S3_CONFIG",
                          options.aws_secret_access_key))
    
    ws_config = {
        "google_key": options.google_key,
        "aws_access_key_id": options.aws_access_key_id,
        "aws_secret_access_key": options.aws_secret_access_key,
        "s3_bucket_region": options.upload_bucket_region,
        "s3_bucket": options.upload_bucket,
        "s3_base_url": "//" + options.upload_bucket + ".s3.amazonaws.com",
        "s3_upload_url": "/images/"
    }
    
    port = int(os.environ.get("PORT", options.port))
    db_url = os.environ.get("CLEARDB_DATABASE_URL",options.db_url)
                    
    control = Control(db_url=db_url,drop_all=True)
    
    handlers = [
        (r"/websocket", WebsocketHandler),
        (r"/login(.*)", LoginHandler),
        (r"/logout", LogoutHandler),
        (r"/config", ConfigHandler, {"config": ws_config }),
        (r"/rest/(.*)", RestHandler,{"auth_header":'simple-auth-token'}),
        (r"/images/(.*)", S3UploadDirectHandler, {
            "bucket": options.upload_bucket,
            "s3_config": s3_config
            }),
        (r"/", IndexHandler),
    ]
    settings = {
        "static_path": resource_filename('examples.simple',"www/static"),
        "template_path": resource_filename('examples.simple',"www/templates"),
        "cookie_secret": 'blueshed.simple-secret',
        "cookie_name": 'blueshed.simple-user',
        "login_url": '/login',
        "gzip": True,
        "control": control,
        "ws_version": WS_VERSION,
        "ws_config": ws_config,
        "debug": options.debug
    }
    
    application = tornado.web.Application(handlers, **settings)
    application.listen(port)
    logging.info("listening on port {}".format(port))
    logging.info("mode:{}".format("production" if options.debug=='no' else 'debug'))
    tornado.ioloop.IOLoop.instance().start()
Beispiel #25
0
def main(config_file="./kew_pe.conf"):
    from tornado import options
    ''' parse the command line - new up the appl and listen on port '''
    if os.path.isfile(config_file):
        print ("Loading config file %s" % config_file)
        options.parse_config_file(config_file)
    options.parse_command_line()
    
    run()
Beispiel #26
0
def parse_options():
    """优先级:命令行 > 安装目录/config.py > /etc/light/net_server.py"""
    if os.path.exists("/etc/light/net_server.py"):
        opts.parse_config_file("/etc/light/net_server.py")
    if os.path.exists(os.path.join(LOCAL_DIR, "config.py")):
        opts.parse_config_file(os.path.join(LOCAL_DIR, "config.py"))
    opts.parse_command_line()
    print "使用配置"
    for k, i in opts.options.as_dict().items():
        print k, "->", i
 def setUpClass(self):
     if "port" not in options:
         define("port", default=8888, type=int)
     if "db" not in options:
         define("db", default=":memory:")
     if "db_echo" not in options:
         define("db_echo", default=True)
     config_file = os.path.join(os.path.dirname(__file__), "test.cfg")
     parse_config_file(config_file)
     models_init()
Beispiel #28
0
 def setUp(self):
     AsyncTestCase.setUp(self)
     for key in options.keys():
         del options[key]
     define_common_options()
     define_node_options()
     parse_config_file(os.path.join(DIR, 'config_data.py'))
     self.init_storages()
     self.node_oid = str(uuid.uuid1())
     Cluster.instance().init()
Beispiel #29
0
def main():
    
    ''' parse the command line - new up the appl and listen on port '''
    if os.path.isfile("kew_pe.conf"):
        print ("Loading config file ./kew_pe.conf")
        options.parse_config_file("kew_pe.conf")
    options.parse_command_line()
        
    logging.basicConfig(level=logging.DEBUG)
    index_control.run('localhost',8081)
Beispiel #30
0
    def run_from_argv(self, prog_name, argv=None, **_kwargs):
        app_settings = settings.APP_SETTINGS
        argv = list(filter(self.flower_option, argv))
        # parse the command line to get --conf option
        parse_command_line([prog_name] + argv)
        try:
            parse_config_file(options.conf, final=False)
            parse_command_line([prog_name] + argv)
        except IOError:
            if options.conf != settings.CONFIG_FILE:
                raise

        app_settings['debug'] = options.debug
        if options.cookie_secret:
            app_settings['cookie_secret'] = options.cookie_secret

        if options.url_prefix:
            prefix = options.url_prefix.strip('/')
            app_settings['static_url_prefix'] = '/{0}/static/'.format(prefix)
            app_settings['login_url'] = '/{0}/login'.format(prefix)
            settings.URL_PREFIX = prefix
        settings.CELERY_INSPECT_TIMEOUT = options.inspect_timeout
        settings.AUTO_REFRESH = options.auto_refresh

        if options.debug and options.logging == 'info':
            options.logging = 'debug'
            enable_pretty_logging()

        # Monkey-patch to support Celery 2.5.5
        self.app.connection = self.app.broker_connection

        self.app.loader.import_default_modules()
        flower = Flower(celery_app=self.app, options=options,
                        **app_settings)
        atexit.register(flower.stop)

        # graceful shutdown on SIGTERM
        def signal_handler(signal, frame):
            logger.info('SIGTERM detected, shutting down')
            sys.exit(0)
        signal.signal(signal.SIGTERM, signal_handler)

        logger.info('Visit me at http%s://%s:%s',
                    's' if flower.ssl else '',
                    options.address or 'localhost',
                    options.port)
        logger.info('Broker: %s', self.app.connection().as_uri())
        logger.debug('Registered tasks: \n%s',
                     pformat(sorted(self.app.tasks.keys())))
        logger.debug('Settings: %s', pformat(app_settings))

        try:
            flower.start()
        except (KeyboardInterrupt, SystemExit):
            pass
Beispiel #31
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tornado import web, ioloop, options
from server.chatroom import ChatRoomHandler

if __name__ == '__main__':
    app = web.Application([
        (r"/", ChatRoomHandler),
    ],
                          websocket_ping_interval=3)

    options.parse_config_file("./config/logger.conf")
    app.listen(8080)
    ioloop.IOLoop.current().start()
Beispiel #32
0
#!/usr/bin/env python
from os import path
from sys import argv

from pyPdf import PdfFileReader
from tornado.options import define, options, parse_config_file

from magpie.config import config_path

define('repo', default=None, type=str)
define('default_notebook', default='', type=str)
parse_config_file(config_path.pdf_scraper)

def scrape(file_path):
    pdf = PdfFileReader(file(file_path, 'rb'))
    content = ''
    for i in range(0, pdf.numPages):
        # TODO figure out why line breaks don't seem to be rendering
        content += pdf.getPage(i).extractText() + '\n'
    out_file = '.%s' % path.basename(file_path)
    out_path = path.join(path.dirname(file_path), out_file)
    if options.repo not in path.commonprefix([out_path, options.repo]):
        out_path = path.join(options.repo, options.default_notebook, out_file)
    content = content.encode('ascii', 'ignore')
    f = open(out_path, 'w')
    f.write(content)
    f.close()

if __name__ == '__main__':
    for file_name in argv[1:]:
        scrape(file_name)
Beispiel #33
0
import os
from tornado.ioloop import IOLoop
from tornado.options import parse_command_line, parse_config_file, options
from msched import make_app
from msched.handlers import TaskHandler, TasksHandler

routes = [(r'/task', TaskHandler), (r'/task/(.*)', TaskHandler),
          (r'/tasks', TasksHandler)]

app = make_app(routes)

if __name__ == '__main__':
    if os.path.exists('/etc/msched/proxy.conf'):
        parse_config_file('/etc/msched/proxy.conf')
    if os.path.exists('./application.conf'):
        parse_config_file('./application.conf')
    parse_command_line()
    app = make_app(routes, debug=True)
    app.listen(options.port, address=options.bind)
    try:
        app.zk.start()
        IOLoop().current().start()
    except KeyboardInterrupt:
        IOLoop().current().stop()
Beispiel #34
0
import logging

import tornado.web
import tornado.ioloop
import tornado.websocket
from tornado import gen, ioloop
from tornado.httpclient import AsyncHTTPClient, HTTPError
from tornado.options import define, options, \
    parse_command_line, parse_config_file

define("port", default=8888, help="run on the given port", type=int)
define("benzinga_endpoint", default="http://data.benzinga.com/stock",
        help="benzinga stock base URL", type=str)

base_dir = os.path.dirname(__file__)
parse_config_file(os.path.join(base_dir, "settings.cfg"))

# list of active trade websocket connections
connections = []


class Main(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.render("index.html")


class Trade(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.render("trade.html")
Beispiel #35
0
define("http_port", default=5000, help="HTTP Port")

define("tornado_secret", help="Tornado Secret")
define("tornado_translations", help="Tornado translations path")
define("tornado_templates", help="Tornado templates path")
define("tornado_static", help="Tornado static path")

define("evesso_clientid", help="EVE SSO client ID")
define("evesso_secretkey", help="EVE SSO secret key")
define("evesso_callback", help="EVE SSO callback URI")

options.define("slack_apitoken", help="Slack API Token")
options.define("slack_username", help="Slack username", default="apoptosis")

parse_config_file("/home/user/apoptosis.conf")  # XXX correct location

auth_name = options.auth_name

redis_host = options.redis_host
redis_port = options.redis_port
redis_database = options.redis_database
redis_password = options.redis_password

database_uri = options.database_uri

http_port = options.http_port

tornado_secret = options.tornado_secret
tornado_translations = options.tornado_translations
tornado_templates = options.tornado_templates
Beispiel #36
0
def main():
    try:
        parse_config_file('/home/wormhole-tracker/wormhole-tracker.conf')
    except Exception as e:  # TODO: specify correct exception here
        logging.warning(e)
        parse_command_line()

    if (not options.client_id or not options.client_key
            or not options.redirect_uri or not options.cookie_secret):
        error = """

Please create configuration file /home/wormhole-tracker/wormhole-tracker.conf
and fill it as follows:

    client_id     = "your_eve_app_id"
    client_key    = "your_eve_app_key"
    redirect_uri  = "http://your-domain-or-ip.com"
    cookie_secret = "my_secret_secret"

For example:

    client_id     = "334jjnn32i23yv23592352352sa3n52b"
    client_key    = "3534ui32b5223yu5u2v35v23v523v3fg"
    redirect_uri  = "http://my-awesome-eve-app.com"  # "http(s)://" IS required!
    cookie_secret = "WYkRXG1RJhmpYlYCA2D99EFRz9lt709t"

Or, if you launch the application via terminal, provide this data
as command line arguments as follows:

    wormhole-tracker --client_id="eve_app_id" \\
                     --client_key="eve_app_key" \\
                     --redirect_uri="https://domain-or-ip.com" \\
                     --cookie_secret="my_secret"

        """
        logging.error(error)
        sys.exit(1)

    settings['cookie_secret'] = options.cookie_secret
    app = App(options.client_id, options.client_key, routes, settings)
    http_server = HTTPServer(app, xheaders=True)

    # TODO: uncomment when obtain db
    #http_server.bind(options.port)
    #http_server.start(0)  # Use one IOLoop per CPU core
    http_server.listen(options.port)

    try:
        logging.info("Starting server...")
        IOLoop.current().start()
    except (SystemExit, KeyboardInterrupt):
        logging.info("Stopping server.")
        IOLoop.current().stop()
        http_client.close()
        sys.exit()

    except Exception as e:
        logging.error(e)
        IOLoop.current().stop()
        http_client.close()
        sys.exit(1)
Beispiel #37
0
import json
import click
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template
from tornado.options import define, options, parse_config_file

__version__ = '0.0.10'

webhook_cnt = 0  # webhook 计数,每次重启都清空
webhook_last = ''
webhook_repo = ''  # webhook hook 哪一个 git 仓库
config_path = '/webhookit/tests/config.py'
define('WEBHOOKIT_CONFIGURE', type=dict)
parse_config_file(config_path)
WEBHOOKIT_CONFIGURE = options.WEBHOOKIT_CONFIGURE


class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        global webhook_cnt, webhook_last, webhook_repo, WEBHOOKIT_CONFIGURE
        config = WEBHOOKIT_CONFIGURE or {}
        config = utils.filter_sensitive(config)
        t = tornado.template.Template(temp.INDEX_HTML_TEMP)
        self.write(
            t.generate(version=__version__,
                       count=webhook_cnt,
                       date=webhook_last,
                       repo=webhook_repo,
                       logs=WSHandler.logs,
Beispiel #38
0
def get_options(env):
    parse_config_file('./algorithm_services/config/{env}.conf'.format(
        env=env, ))
    return options
Beispiel #39
0
import os
import json
import datetime
from tornado import web
from tornado import gen
from tornado import escape
from tornado.web import asynchronous
from tornado.options import parse_command_line, options, parse_config_file
import tornado.ioloop
import tornado.log
from tornado.websocket import WebSocketHandler
from libs.geo import GeoFetch
from tornado.httpclient import AsyncHTTPClient

github_data = {}
parse_config_file("config.py")
parse_config_file("settings.py")

import workers


class ApiHandler(web.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ApiHandler, self).__init__(*args, **kwargs)
        super(ApiHandler, self).set_header('Content-Type', 'application/json; charset=UTF-8')
        
    def prepare(self):
        """do something before request comming"""
        #options.logger.debug(self.request)
        pass
Beispiel #40
0
        self.write('<a href="/python">hello python</a>')

    # 响应以post方式发送的请求
    def post(self, *args, **kwargs):
        pass


# 演示配置文件配置

# 定义一个变量,用来代表端口号,若配置文件中找不到port,则使用default  multiple 是否为多个元素
define('port', type=int, default=11111, multiple=False)
# 再定义一个变量,用来代表连接数据库的连接信息(用户名,密码,端口,数据库名称)
define('db', multiple=True, default=[])

# 从指定的配置文件中,读取配置文件中的内容
parse_config_file('configure')
print(options.db)
print(options.port)

# 演示路由列表

# 创建application对象,进行对若干个服务器的设置
# 例如,路由列表 静态资源路径 模板路径

app = Application([
    ('/', IndexHandler),
])

# 演示服务器配置

# 创建服务器程序
Beispiel #41
0
from modelrunner import (config, WorkerServer, Dispatcher, __version__)

from modelrunner.settings import (initialize, redis_connection, job_queue_name,
                                  node_channel_name, all_nodes_channel_name)

from tornado.options import parse_command_line, parse_config_file

# setup log
logger = logging.getLogger('modelrunner')

logger.info("modelrunner %s (Python %s)" %
            (__version__, '.'.join(map(str, sys.version_info[:3]))))

# so we can load config via cmd line args
parse_command_line()
parse_config_file(config.options.config_file)

# initialize the global application settings
initialize(config.options.redis_url)

# get the command_ keys
command_dict = config.options.group_dict("model_command")

worker_handler = WorkerServer(config.options.worker_url,
                              config.options.data_dir, config.options.model,
                              command_dict)
channels = [
    node_channel_name(worker_handler.node.name),
    all_nodes_channel_name()
]
worker = Dispatcher(redis_connection(), worker_handler,
Beispiel #42
0
import tornado.escape
import tornado.gen
import tornado.httpclient
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import urlparse

from image import Image, ImageFormatError
from signature import verify_signature

from tornado.options import define, options, parse_config_file

define("config", help="path to configuration file", type=str,
       callback=lambda path: parse_config_file(path, final=False))
define("debug", default=False, help="run in debug mode", type=bool)
define("port", default=8888, help="run on the given port", type=int)
define("client_name", help="client name", type=str)
define("client_key", help="client key", type=str)
define("allowed_hosts", default=[], help="list of allowed image hosts",
       type=str, multiple=True)


logger = logging.getLogger("tornado.application")


class PilboxApplication(tornado.web.Application):
    TESTDATADIR = os.path.join(os.path.dirname(__file__), "test", "data")

    def __init__(self, **kwargs):
        #msg=empty
        #msg=duplicate
        print('query', q)
        #msg = q.split('=')[1]
        #msg = q[4:]
        msg = q[q.find('=') + 1:]
        if msg == 'empty':
            result = '请输入完整'
        if msg == 'duplicate':
            result = '用户名重复'

        return self.render_string('mymodule/regist_module.html', result=result)


define('port', type=int, default=8888)
parse_config_file('config/config')

app = Application(
    [('/', IndexHandler), ('/login', LoginHandler), ('/blog', BlogHandler),
     ('/regist', RegistHandler)],
    template_path=join(dirname(__file__), 'mytemplate'),
    ui_modules={
        'loginmodule': LoginModule,
        'blogmodule': BlogModule,
        'registmodule': RegistModule
    },
    static_path='mystatics')
server = HTTPServer(app)
server.listen(options.port)
IOLoop().current().start()
Beispiel #44
0

def create_router():
    from dispatcher.patientapi import PatientRouter
    app_router = PatientRouter()
    from dispatcher.nursepanel import NurseRouter
    app_router.append(NurseRouter())
    from dispatcher.adminpanel import AdminRouter
    app_router.append(AdminRouter())
    return app_router


if __name__ == '__main__':
    """Serves as the main entry point to launch the webservice."""
    if options.mode is 'test':
        parse_config_file(os.path.join('.', 'config', 'testconfig.py'))
    else:
        parse_config_file(os.path.join('.', 'config', 'devconfig.py'))
    parse_command_line()

    from tornado_sqlalchemy import make_session_factory
    factory = make_session_factory(options.db)

    # Assemble the tornado application with its submodules
    app_router = None
    try:
        app_router = create_router()
    except KeyError as e:
        print(e)
        exit(1)
Beispiel #45
0
# 用来定义变量的


class IndexHandler(web.RequestHandler):
    def data_received(self, chunk):
        pass

    def get(self, *args, **kwargs):
        self.write('<h1 align="center">你说的和你表达的不一样:app_8000</h1>')


if __name__ == '__main__':
    # 转换命令行参数
    # options.parse_command_line()
    options.parse_config_file('config.cfg')
    # options.options.logging = 'INFO'

    log_config = yaml.load(open('logging.yaml', 'r'))

    print(log_config)

    config.dictConfig(log_config)

    # print(options.options.list)
    app = web.Application([(r'/index', IndexHandler)])
    # app.listen(port=8000, address='0.0.0.0')

    # 实例化一个httpServer
    http_server = httpserver.HTTPServer(app)
Beispiel #46
0
                            "SELECT host(ip) FROM %s where user_id=%i;" % (options.TABLE_NAME, uid))
                        for ips in cursor.fetchall():
                            self.rc.sadd(uid, ips[0])
                    if self.rc.scard(first_user_id) > self.rc.scard(second_user_id):
                        self.rc.sadd('Related', sstring)
                        result = True

        self.write("Users %i and %i are related: %s." % (
            first_user_id, second_user_id,
            result
        ))
        self.finish()

if __name__ == "__main__":
    try:
        parse_config_file('config.conf')
    except:
        logging.info('Config file ./config.conf not found')

    application = tornado.web.Application([
        (r"/user_relations/", MainHandler),
    ])

    ioloop = tornado.ioloop.IOLoop.instance()

    if options.USE_RC:
        redisConnectionPool = redis.ConnectionPool(
            host='localhost',
            port=6379, db=12
        )
        application.rc = redis.Redis(connection_pool=redisConnectionPool)
Beispiel #47
0
        settings = dict(
            ui_modules={},
            debug=True,
        )
        super(Application, self).__init__(handlers, **settings)


if __name__ == "__main__":
    # judger = subprocess.Popen( ['./tradiJudger', \
    # 							'--tl=1', '--ml=256', '--ol=64',\
    # 							'--in-pre=test', '--in-suf=in',\
    # 							'--out-pre=test', '--out-suf=out',\
    # 							'--Lang=C++',\
    # 							'--data-dir=/home/ycdfwzy/myworkspace/tinyjudger/test/',\
    # 							'--checker=ncmp',  '--n-tests=2', '--source-name=test',\
    # 							'--source-dir=/home/ycdfwzy/myworkspace/tinyjudger/test/'
    # 							], stdout=subprocess.PIPE)
    # time.sleep(1)
    # judger.kill()
    tornado.options.parse_command_line()
    options.parse_config_file('configs.py')
    # print(options.domain)

    traditioanlJudgerThread = Thread(target=handleTraditionalJudger)
    scriptJudgerJudgerThread = Thread(target=handleScriptJudger)
    traditioanlJudgerThread.start()
    scriptJudgerJudgerThread.start()
    app = Application()
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start()
Beispiel #48
0
"""

# DO NOT REMOVE
import bitsd.properties

from bitsd.persistence.engine import session_scope
from bitsd.persistence import start
from bitsd.server.auth import useradd, userdel, usermod
from tornado.options import parse_config_file

import sys
from getpass import getpass

if __name__ == '__main__':
    try:
        parse_config_file('/etc/bitsd.conf')
    except IOError:
        print("[INFO] No /etc/bitsd.conf found, ignoring.")

    action = sys.argv[1]
    username = sys.argv[2]

    start()

    with session_scope() as session:
        if action == 'add':
            password = getpass('Password for `{}`:'.format(username))
            useradd(session, username, password)
        elif action == 'delete':
            userdel(session, username)
        elif action == 'modify':
Beispiel #49
0
define('notify_errors', True)
define('error_email', [
    '*****@*****.**',
], multiple=True)
define('feedback_email', [
    '*****@*****.**',
], multiple=True)

# Email AWS SES
define('from_email', '*****@*****.**')
define('aws_access_key_id', '')
define('aws_secret_access_key', '')
define('aws_region', 'us-east-1')

# load the local override config
local_override = os.path.join(CONFIGS_DIR, '{}.config.py'.format(ENVIRONMENT))

if os.path.isfile(local_override):
    parse_config_file(local_override, final=False)

# load the cli flags to override pre-defined config settings
# remove app.py if it is the first arg. This is done because starting the sever
# by running python app.py start_server --arg=value is not parsable by
# tornado's parse_command_line function
args = sys.argv[:]

if args[0] == 'app.py':
    args = args[1:]

parse_command_line(args=args)
Beispiel #50
0
define("db_name", type=str)
define("db_user", type=str)
define("db_password", type=str)
define("db_host", type=str)
define("db_port", type=str)

define("template_path", type=str)
define("debug", type=str)
define("filestore", type=str)

define("size_db_connection_pool", type=int)
define("cache_host", type=str)
define("cache_port", type=int)
define("cache_db", type=int)

parse_config_file("application.conf")
tornado.options.parse_command_line()

import urls

if __name__ == '__main__':
    tornado.log.enable_pretty_logging()

    if options.debug == "yes":
        tornado.log.app_log.setLevel(logging.DEBUG)
    elif options.debug == "no":
        tornado.log.app_log.setLevel(logging.INFO)

    tornado.platform.asyncio.AsyncIOMainLoop().install()

    application = Application(
Beispiel #51
0
from magpie.config import config_path


class EmailNotesError(Exception):
    pass


define('imap_server', default=None, type=str)
define('username', default=None, type=str)
define('password', default=None, type=str)
define('folder', default=None, type=str)
define('repo', default=None, type=str)
define('use_ssl', default=True, type=bool)
define('default_notebook', default='', type=str)
parse_config_file(config_path.email_notes)

if options.use_ssl:
    imap = IMAP4_SSL(options.imap_server)
else:
    imap = IMAP4(options.imap_server)
imap.login(options.username, options.password)

result, data = imap.select(options.folder)
if result != 'OK':
    raise EmailNotesError(result)
result, messages = imap.search(None, '(UNSEEN)')
if result != 'OK':
    raise EmailNotesError(result)

if messages[0] == '':
Beispiel #52
0
import json
from random import randint

from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options import define, parse_config_file, options
from tornado.web import Application, RequestHandler

define("PORT",type=int,default=8888)
parse_config_file("../config/config")


class IndexHandler(RequestHandler):
    def get(self, *args, **kwargs):
        res = ''
        msg = self.get_query_argument("msg", None)
        if msg:
            res = '用户名或密码错误'
        self.render('login.html',result=res)

class LoginHandler(RequestHandler):
    def post(self, *args, **kwargs):
        username = self.get_body_argument("username")
        pwd = self.get_body_argument("pwd")

        if username=="ding" and pwd=="123":
            files = self.request.files
            if files:
                avatars = files.get("avatar")
                for avatar in avatars:
                    filename = avatar.get("filename")
Beispiel #53
0
        logging.debug('Message will be sent on url %s' % options.serverurl)
        httpClient = tornado.httpclient.AsyncHTTPClient()
        postRequest = tornado.httpclient.HTTPRequest(
            url=options.serverurl,
            method="POST",
            body=json.dumps(response),
            headers=tornado.httputil.HTTPHeaders({
                "content-type": "application/json",
                "method": "POST"
            }))
        response = yield httpClient.fetch(postRequest)
        self.sendedMessage(response)


if __name__ == '__main__':
    parse_config_file(os.path.abspath('') + '/options.conf')
    logging.basicConfig(level=logging.DEBUG)
    tornado.httpclient.AsyncHTTPClient.configure(
        "tornado.curl_httpclient.CurlAsyncHTTPClient")
    ioloop = tornado.ioloop.IOLoop.instance()
    api = requests.Session()
    application = app([
        (r"/", mainHandler),
    ])

    url = options.url % options.token + "setWebhook?url=%s" % options.myurl
    files = {
        'certificate': open('/usr/share/nginx/qa_bot/qa_bot_company.pem', 'rb')
    }
    set_hook = api.post(url, files=files)
    if set_hook.status_code != 200:
Beispiel #54
0
define("cache_engine", default="apps.core.cache.memory.MemoryCache")
define("cache_options", default=dict())

define("process_num", default=0)  # 0即CPU个数
define("broker_transport", default="redis")
define("broker_url", default="redis://127.0.0.1:6379/0")
define("result_backend", default="redis://127.0.0.1:6379/0")
define("celery_task_result_expires", type=int, default=1800)
define("celery_max_cached_results", type=int, default=300)
define("celery_timezone", default='Asia/Shanghai')
define("celeryd_concurrency", type=int, default=6)
define("accept_content", type=list, default=['pickle', 'json'])
define("task_serializer", default='pickle')


parse_config_file("conf/app.conf")


class LogOption(dict):

    def __missing__(self, key):
        return dict.get(self, key)

    def __getattr__(self, key):
        return self.get(key)

    def __setattr__(self, key, value):
        if key in self:
            self[key] = value
        else:
            return super(LogOption, self).__setattr__(key)
Beispiel #55
0
    def get(self):
        self.write('Hello Python')
        #GET获取参数 http://127.0.0.1:9999/python?day=111111111
        day = self.get_query_argument('day', default='0000000', strip=False)
        print(self.request)
        self.write('Hello Python' + day)
        #/python?day=1&day=2&day=3&day=4&day=5
        day = self.get_query_arguments('day', strip=False)
        print(day)  #[1,2,3,4,5]

    #覆盖RequestHandler  post方法,响应post请求
    def post(self):
        day = self.get_body_argument('day', default='0000000', strip=False)
        self.write('Hello Python' + day)
        day = self.get_body_arguments('day', strip=False)
        print(day)


define('port', type=int, default=8888)

parse_config_file('config/config.txt')

app = Application(handlers=[('/', IndexHandler), (
    '/java', JavaHandler), ('/java/([0-9]*)/([a-z0-9]*)',
                            JavaHandler), ('/python', PythonHandler)])

server = HTTPServer(app)
server.listen(options.port)

IOLoop.current().start()
Beispiel #56
0
def options():
    '''
        Fiorella monkey configuration options
    '''
    tornado.options.define('ensure_indexes', 
        default=True, type=bool,
        help=('Ensure collection indexes'))

    # Set config and stuff
    tornado.options.define('config', 
        type=str, help='path to config file',
        callback=lambda path: parse_config_file(path, final=False))

    # debugging
    tornado.options.define('debug',
        default=False, type=bool,
        help=('Turn on autoreload and log to stderr only'))

    # logging dir
    tornado.options.define('logdir',
        type=str, default='log',
        help=('Location of logging (if debug mode is off)'))

    tornado.options.define('domain',
        default='iofun.io', type=str,
        help='Application domain, e.g: "example.com"')

    # Server settings
    tornado.options.define('host', 
        default='127.0.0.1', type=str,
        help=('Server hostname'))

    tornado.options.define('port',
        default=8888, type=int,
        help=('Server port'))

    # Overlord node settings
    tornado.options.define('overlord_host', default='127.0.0.1', type=str,
                            help=('Overlord hostname or ip address'))

    tornado.options.define('overlord_port', default=8899, type=int,
                            help=('Overlord port'))

    # MongoDB database settings
    tornado.options.define('mongo_host',
        type=str, help=('MongoDB hostname or ip address'))

    tornado.options.define('mongo_port', 
        default=27017, type=int,
        help=('MongoDB port'))

    # PostgreSQL database settings
    tornado.options.define('sql_host',
        type=str, help=('PostgreSQL hostname or ip address'))

    tornado.options.define('sql_port',
        default=5432, type=int,
        help=('PostgreSQL port'))

    tornado.options.define('sql_database',
        type=str, help=('PostgreSQL database'))

    tornado.options.define('sql_user',
        type=str, help=('PostgreSQL username'))

    tornado.options.define('sql_password',
        type=str, help=('PostgreSQL username password'))

    tornado.options.define('memcached_host',
        default='127.0.0.1', type=str,
        help=('Memcached host'))

    tornado.options.define('memcached_port',
        default=11211, type=int,
        help=('Memcached port'))

    tornado.options.define('memcached_binary',
        default=True, type=bool,
        help=('Memcached binary'))

    tornado.options.define('memcached_tcp_nodelay',
        default=True, type=bool,
        help=('Memcached tcp_nodelay'))

    tornado.options.define('memcached_ketama',
        default=True, type=bool,
        help=('Memcached ketama'))

    tornado.options.define('cache_enabled',
        default=False, type=bool,
        help=('Enable cache'))
    
    # ZMQ external PUB logger
    tornado.options.define('external_log',
        default=False, type=bool,
        help=('External logger'))

    tornado.options.define('base_url',
        default='api', type=str,
        help=('Base url, e.g. "api"'))

    tornado.options.define('page_size',
        default=20, type=int,
        help=('Set a custom page size up to 100'))

    tornado.options.define('cookie_secret',
        default=secret, type=str,
        help=('Secure cookie secret string'))

    # this need to change to mailgun_key and mailgun_api

    tornado.options.define('api_key',
        default='key-348c3d4a39568cd19c1c7e41ff6944d4',
        type=str,
        help=('Secure key mailgun'))

    tornado.options.define('api_url',
        default="https://api.mailgun.net/v3/codemachine.io/messages",
        type=str,
        help=('Mail API URL'))

    tornado.options.define('max_retries',
        default=2, type=int,
        help=('Max retries'))
    
    tornado.options.define('retry_time',
        default=300, type=int,
        help=('Outbound calling retry time'))

    tornado.options.define('wait_time',
        default=45, type=int,
        help=('Wait time'))

    tornado.options.define('max_calls',
        default=10, type=int,
        help=('Maximum number of concurrent calls'))

    tornado.options.define('asterisk_user',
        default='asterisk', type=str,
        help=('non-root Asterisk user'))

    tornado.options.define('asterisk_group',
        default='asterisk', type=str,
        help=('non-root Asterisk group'))

    tornado.options.define('spool_dir',
        default='/var/spool/asterisk/outgoing/', type=str,
        help=('Asterisk spool dir'))

    tornado.options.define('tmp_dir',
        default='/tmp/', type=str,
        help=('tmp outbound call files'))

    tornado.options.define('server_delay', default=2.0)

    tornado.options.define('client_delay', default=1.0)

    tornado.options.define('num_chunks', default=40)

    # Parse config file, then command line...
    # so command line switches take precedence
    if os.path.exists(config_path):
        print('Loading', config_path)
        tornado.options.parse_config_file(config_path)
    else:
        print('No config file at', config_path)

    tornado.options.parse_command_line()
    result = tornado.options.options

    for required in (
        'domain', 'host', 'port', 'base_url',
    ):
        if not result[required]:
            raise Exception('%s required' % required)

    return result
Beispiel #57
0
def get_options():
    #Application
    options.define("configfilename",
                   default="tpaste.conf",
                   type=str,
                   help="Configuration filename")
    options.define('debug',
                   default=True,
                   type=bool,
                   help="Turn on autoreload, log to stderr only")
    options.define("port", default=8888, type=int, help="Tornado server port")
    options.define('cookie_secret',
                   default=base64.b64encode(os.urandom(32)),
                   type=str,
                   help="Secret seed for cookies")
    options.define('static_url_prefix',
                   default=None,
                   type=str,
                   help="Useful for serve static files from separate server.")
    options.define("theme_path",
                   default="theme",
                   type=str,
                   help="Theme path with static files and templates")
    options.define("googleanalytics_enabled",
                   default=True,
                   type=bool,
                   help="Enable Google Analytics module")
    options.define("googleanalytics_trackercode",
                   default="",
                   type=str,
                   help="Set Google Analytics tracker code")
    options.define('base_url',
                   default="http://localhost",
                   type=str,
                   help="Base url host")
    options.define('slogan',
                   default="Web application for saving and sharing "
                   "text snippets. Using Tornado, MongoDB and Motor.",
                   type=str,
                   help="Slogan")

    #MongoDB
    options.define('db_uri',
                   default='mongodb://*****:*****@puentesarr.in",
                   type=str,
                   help="SMTP username connection")
    options.define('smtp_password',
                   default="fonoavisos",
                   type=str,
                   help="SMTP password connection")

    if os.path.exists(options.options.configfilename):
        options.parse_config_file(options.options.configfilename)
    else:
        raise Exception(
            'No config file at %s.' %
            os.path.join(os.getcwd(), options.options.configfilename))

    options.parse_command_line()
    return options.options
Beispiel #58
0
def load_options(args=None):
    parse_command_line(args=args)
    if options.config_file:
        parse_config_file(options.config_file)
Beispiel #59
0
        pass

class PythonHandler(RequestHandler):
    def get(self,  p1=None, p2=None, *args, **kwargs):
        self.write('hello python <br>')
        if p1:
            self.write('date:' + p1 + '<br>')
        if p2:
            self.write('subject:' + p2 + '<br>')

    def post(self, *args, **kwargs):
        pass
# 定义配置文件中的内容
define('port', type=int, default=8888)
# 指定配置文件路径
parse_config_file('../config/conf')

# 创建Application对象,Application是Tornado最核心的类
# 所有关于服务器的配置信息都要写在Application构造器中
# 以构造器的参数形式传入
# 比如:路由列表
# 路由列表的作用是告诉Tornado,对特定路径的请求,由哪个类进行响应
app = Application([('/', IndexHandler),
                   ('/python', PythonHandler),
                   ('/python/([0-9a-zA-Z]+)', PythonHandler),
                   ('/python/([0-9a-zA-Z]+)/([a-zA-Z]+)', PythonHandler),
                   ])
# 创建真正的服务器程序
server = HTTPServer(app)
server.listen(options.port) # 从配置文件中读取port
Beispiel #60
0
def main():
    parse_config_file(os.path.abspath('') + '/options.conf')

    print(options.serverurl)