def parse_config(self): """Parses the command line arguments, and assign their values to our local traits. """ if not self.command_line_options_inited: for traitlet_name, traitlet in self.traits().items(): define( traitlet_name, default=traitlet.default_value, type=type(traitlet.default_value), help=traitlet.help) self.__class__.command_line_options_inited = True tornado.options.parse_command_line() # Workaround for change in jupyterhub 0.7.0. # Args are passed with quotes, that are preserved in the arguments when # we retrieve them. We just get rid of the quotes, until a better # solution comes along. # See jupyterhub/jupyterhub#836 for details. opts = {k: remove_quotes(v) for k, v in options.as_dict().items()} set_traits_from_dict(self, opts) # Normalize the base_urlpath to end with a slash self.base_urlpath = with_end_slash(self.base_urlpath)
def main(config_file=None): # noinspection PyUnresolvedReferences import frontik.options parse_configs_and_start(config_files=config_file) if options.app is None: log.exception('no frontik application present (`app` option is not specified)') sys.exit(1) try: module = importlib.import_module(options.app) except Exception as e: log.exception('failed to import application module "%s": %s', options.app, e) sys.exit(1) if options.app_class is not None and not hasattr(module, options.app_class): log.exception('application class "%s" not found', options.app_class) sys.exit(1) application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication try: tornado_app = application(**options.as_dict()) except: log.exception('failed to initialize frontik application, quitting') sys.exit(1) run_server(tornado_app)
def main(): tornado.options.parse_command_line() handlers = [ tornado.web.url(r'/', StubHandler, name='index'), ] settings = dict( #... **options.as_dict()) application = tornado.web.Application(handlers=handlers, **settings) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) http_server.listen(8081) loop = tornado.ioloop.IOLoop.instance() try: loop_status = loop.start() except KeyboardInterrupt: loop_status = loop.stop() return loop_status
def main(config_file=None): # noinspection PyUnresolvedReferences import frontik.options parse_configs_and_start(config_files=config_file) if options.app is None: log.exception( 'no frontik application present (`app` option is not specified)') sys.exit(1) try: module = importlib.import_module(options.app) except Exception as e: log.exception('failed to import application module "%s": %s', options.app, e) sys.exit(1) if options.app_class is not None and not hasattr(module, options.app_class): log.exception('application class "%s" not found', options.app_class) sys.exit(1) application = getattr( module, options.app_class ) if options.app_class is not None else FrontikApplication try: tornado_app = application(**options.as_dict()) except: log.exception('failed to initialize frontik application, quitting') sys.exit(1) run_server(tornado_app)
def __init__(self): root_path = os.path.dirname(__file__) self.static_path = os.path.join(root_path, 'static') self.tmp_path = os.path.join(root_path, 'tmp') self.media_path = os.path.join(root_path, 'media') self.upload_path = os.path.join(self.media_path, 'upload') handlers = [ (r'/', SiteHandler, { 'path': os.path.join(self.static_path, 'starter.html') }), (r"/media/(.*)", tornado.web.StaticFileHandler, { 'path': self.media_path }), (r'/upload_to/(?P<category>\w+)', UploadHandler), (r'/app/icon/set', AppIconSetHandler), (r'/icon/merge', IconMergeHandler), (r'/watermark', WatermarkHandler), ] settings = dict( static_path=os.path.join(root_path, 'static'), xsrf_cookies=False, cookie_secret='VAgYv0fQ5KLKdVUH7OlGHUTkOq9DZbSY', ) if not options.debug: settings['cookie_secret'] = str(uuid.uuid4()) if not os.path.exists(self.tmp_path): os.makedirs(self.tmp_path) settings.update(options.as_dict()) super(Application, self).__init__(handlers, **settings)
def main(): tornado.options.parse_command_line() handlers = [ tornado.web.url(r'/', StubHandler, name='index'), ] settings = dict( #... **options.as_dict() ) application = tornado.web.Application(handlers=handlers, **settings) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) http_server.listen(8081) loop = tornado.ioloop.IOLoop.instance() try: loop_status = loop.start() except KeyboardInterrupt: loop_status = loop.stop() return loop_status
def parse_config(self): """Parses the command line arguments, and assign their values to our local traits. """ if not self.command_line_options_inited: for traitlet_name, traitlet in self.traits().items(): define(traitlet_name, default=traitlet.default_value, type=type(traitlet.default_value), help=traitlet.help) self.__class__.command_line_options_inited = True tornado.options.parse_command_line() # Workaround for change in jupyterhub 0.7.0. # Args are passed with quotes, that are preserved in the arguments when # we retrieve them. We just get rid of the quotes, until a better # solution comes along. # See jupyterhub/jupyterhub#836 for details. opts = {k: remove_quotes(v) for k, v in options.as_dict().items()} set_traits_from_dict(self, opts) # Normalize the base_urlpath to end with a slash self.base_urlpath = with_end_slash(self.base_urlpath)
def __init__(self, service): settings = dict(debug=True) settings.update(options.as_dict()) client = obelisk.ObeliskOfLightClient(service) self.obelisk_handler = obelisk_handler.ObeliskHandler(client) self.brc_handler = broadcast.BroadcastHandler() self.json_chan_handler = jsonchan.JsonChanHandler() self.ticker_handler = ticker.TickerHandler() handlers = [ # /block/<block hash> (r"/block/([^/]*)(?:/)?", rest_handlers.BlockHeaderHandler), # /block/<block hash>/transactions (r"/block/([^/]*)/transactions(?:/)?", rest_handlers.BlockTransactionsHandler), # /tx/ (r"/tx(?:/)?", rest_handlers.TransactionPoolHandler), # /tx/<txid> (r"/tx/([^/]*)(?:/)?", rest_handlers.TransactionHandler), # /address/<address> (r"/address/([^/]*)(?:/)?", rest_handlers.AddressHistoryHandler), # /height (r"/height(?:/)?", rest_handlers.HeightHandler), # / (r"/", QuerySocketHandler) ] tornado.web.Application.__init__(self, handlers, **settings)
def main(): tornado.options.parse_command_line() app = Application(default_handler_class=NotFoundHandler) app.listen(options.port) start_info = 'Server started at :{}'.format(options.as_dict()['port']) print(start_info) tornado.ioloop.IOLoop.current().start()
def main(): tornado.options.parse_command_line() ## ┏━┓┏━╸╺┳╸╺┳╸╻┏┓╻┏━╸┏━┓ ## ┗━┓┣╸ ┃ ┃ ┃┃┗┫┃╺┓┗━┓ ## ┗━┛┗━╸ ╹ ╹ ╹╹ ╹┗━┛┗━┛ code_path = os.path.dirname(__file__) static_path = os.path.join(code_path, 'static') template_path = os.path.join(code_path, 'templates') support_path = os.path.join(code_path, 'support') settings = dict( gzip = True, static_path = static_path, template_path = template_path, support_path = support_path, xsrf_cookies = True, **options.as_dict() ) tornado.log.gen_log.debug(settings) ## ┏━┓┏━┓┏━┓╻ ╻┏━╸┏━┓╺┳╸╻┏━┓┏┓╻ ## ┣━┫┣━┛┣━┛┃ ┃┃ ┣━┫ ┃ ┃┃ ┃┃┗┫ ## ╹ ╹╹ ╹ ┗━╸╹┗━╸╹ ╹ ╹ ╹┗━┛╹ ╹ handlers = [ tornado.web.url(r'/static/(css/.*)', tornado.web.StaticFileHandler, {'path': static_path}), tornado.web.url(r'/static/(ico/.*)', tornado.web.StaticFileHandler, {'path': static_path}), tornado.web.url(r'/static/(img/.*)', tornado.web.StaticFileHandler, {'path': static_path}), tornado.web.url(r'/static/(js/.*)', tornado.web.StaticFileHandler, {'path': static_path}), tornado.web.url(r'/__stub__$', StubHandler), #tornado.web.url(r'/(.*)', PageErrorHandler, kwargs=dict(error=404)), ] application = tornado.web.Application(handlers=handlers, **settings) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) if options.debug: http_server.listen(options.listen_port, address=options.listen_host) else: http_server.bind(options.listen_port, address=options.listen_host) http_server.start(0) application.dsn = options.postgresql_dsn application.db = momoko.Pool( dsn=options.postgresql_dsn, ) loop = tornado.ioloop.IOLoop.instance() try: loop_status = loop.start() except KeyboardInterrupt: loop_status = loop.stop()
def get_app(self): """ Create Lex instance of tornado.web.Application. """ routes = [ URLSpec(r'/globo/', DummyHandler), URLSpec(r'/globo_timeout/', TimeoutHandler) ] return Application(routes, **options.as_dict())
def __init__(self, service): settings = dict(debug=True) settings.update(options.as_dict()) # legacy support if config.get('legacy-url', False): if ws_legacy_enabled: self.ws_client = LegacyClient("wss://" + config.get('legacy-url')) else: print "legacy-url is configured but autobahn not installed" self.ws_client = False client = obelisk.ObeliskOfLightClient(service) self.obelisk_handler = obelisk_handler.ObeliskHandler( client, self.ws_client) self.brc_handler = broadcast.BroadcastHandler() self.p2p = CryptoTransportLayer(config.get('p2p-port', 8889), config.get('external-ip', '127.0.0.1'), config.get('internal-ip', None)) self.p2p.join_network(config.get('seeds', [])) self.json_chan_handler = jsonchan.JsonChanHandler(self.p2p) self.ticker_handler = ticker.TickerHandler() handlers = [ # /block/<block hash> (r"/block/([^/]*)(?:/)?", rest_handlers.BlockHeaderHandler), # /block/<block hash>/transactions (r"/block/([^/]*)/transactions(?:/)?", rest_handlers.BlockTransactionsHandler), # /tx/ (r"/tx(?:/)?", rest_handlers.TransactionPoolHandler), # /tx/<txid> (r"/tx/([^/]*)(?:/)?", rest_handlers.TransactionHandler), # /address/<address> (r"/address/([^/]*)(?:/)?", rest_handlers.AddressHistoryHandler), # /height (r"/height(?:/)?", rest_handlers.HeightHandler), # /height (r"/status(?:/)?", status.StatusHandler, { "app": self }), # / (r"/", QuerySocketHandler) ] tornado.web.Application.__init__(self, handlers, **settings)
def main(config_file=None): # noinspection PyUnresolvedReferences import frontik.options parse_configs(config_files=config_file) if options.app is None: log.exception('no frontik application present (`app` option is not specified)') sys.exit(1) log.info('starting application %s', options.app) try: module = importlib.import_module(options.app) except Exception as e: log.exception('failed to import application module "%s": %s', options.app, e) sys.exit(1) if options.app_class is not None and not hasattr(module, options.app_class): log.exception('application class "%s" not found', options.app_class) sys.exit(1) application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication try: tornado_app = application(**options.as_dict()) ioloop = tornado.ioloop.IOLoop.current() def _run_server_cb(future): if future.exception() is not None: log.error('failed to initialize application, init_async returned: %s', future.exception()) sys.exit(1) run_server(tornado_app) def _async_init_cb(): try: ioloop.add_future(tornado_app.init_async(), _run_server_cb) except Exception: log.exception('failed to initialize application') sys.exit(1) ioloop.add_callback(_async_init_cb) ioloop.start() except: log.exception('frontik application exited with exception') sys.exit(1)
def __init__(self, service): settings = dict(debug=True) settings.update(options.as_dict()) # legacy support if config.get('legacy-url', False): if ws_legacy_enabled: self.ws_client = LegacyClient("wss://"+config.get('legacy-url')) else: print "legacy-url is configured but autobahn not installed" self.ws_client = False client = obelisk.ObeliskOfLightClient(service) self.obelisk_handler = obelisk_handler.ObeliskHandler(client, self.ws_client) self.brc_handler = broadcast.BroadcastHandler() self.p2p = CryptoTransportLayer(config.get('p2p-port', 8889), config.get('external-ip', '127.0.0.1'), config.get('internal-ip', None)) self.p2p.join_network(config.get('seeds', [])) self.json_chan_handler = jsonchan.JsonChanHandler(self.p2p) self.ticker_handler = ticker.TickerHandler() handlers = [ # /block/<block hash> (r"/block/([^/]*)(?:/)?", rest_handlers.BlockHeaderHandler), # /block/<block hash>/transactions (r"/block/([^/]*)/transactions(?:/)?", rest_handlers.BlockTransactionsHandler), # /tx/ (r"/tx(?:/)?", rest_handlers.TransactionPoolHandler), # /tx/<txid> (r"/tx/([^/]*)(?:/)?", rest_handlers.TransactionHandler), # /address/<address> (r"/address/([^/]*)(?:/)?", rest_handlers.AddressHistoryHandler), # /height (r"/height(?:/)?", rest_handlers.HeightHandler), # /height (r"/status(?:/)?", status.StatusHandler, {"app": self}), # / (r"/", QuerySocketHandler) ] tornado.web.Application.__init__(self, handlers, **settings)
def main(): tornado.options.parse_command_line() ## ┏━┓┏━╸╺┳╸╺┳╸╻┏┓╻┏━╸┏━┓ ## ┗━┓┣╸ ┃ ┃ ┃┃┗┫┃╺┓┗━┓ ## ┗━┛┗━╸ ╹ ╹ ╹╹ ╹┗━┛┗━┛ static_path = 'static' template_path = 'templates' handlers = [ ## Static File Serving tornado.web.url(r'/static/(css/.*)', tornado.web.StaticFileHandler, {'path': static_path}), tornado.web.url(r'/static/(ico/.*)', tornado.web.StaticFileHandler, {'path': static_path}), tornado.web.url(r'/static/(img/.*)', tornado.web.StaticFileHandler, {'path': static_path}), tornado.web.url(r'/static/(js/.*)', tornado.web.StaticFileHandler, {'path': static_path}), ## Main tornado.web.url(r'/(.*)$', TemplateHandler, name='template'), ] settings = dict( ui_modules = {'static_file_data_uri_base64': tornado_data_uri.uimodules.static_file_data_uri_base64}, **options.as_dict() ) tornado.log.gen_log.debug(pprint.pformat(settings)) ## ┏━┓┏━┓┏━┓╻ ╻┏━╸┏━┓╺┳╸╻┏━┓┏┓╻ ## ┣━┫┣━┛┣━┛┃ ┃┃ ┣━┫ ┃ ┃┃ ┃┃┗┫ ## ╹ ╹╹ ╹ ┗━╸╹┗━╸╹ ╹ ╹ ╹┗━┛╹ ╹ application = tornado.web.Application(handlers=handlers, **settings) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) http_server.listen(options.listen_port, address=options.listen_host) loop = tornado.ioloop.IOLoop.instance() try: loop_status = loop.start() except KeyboardInterrupt: loop_status = loop.stop() return loop_status
def __init__(self, db_session): handlers = [ url(r'/login', LoginHandler, name='login'), url(r'/join', RegisterHandler, name='register'), url(r'/logout', LogoutHandler, name='logout'), url(r'/home', HomeHandler, name='home'), ] settings = dict( template_path=os.path.join(os.path.dirname(__file__), 'templates'), static_path=os.path.join(os.path.dirname(__file__), 'static'), xsrf_cookies=True, cookie_secret='__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__', login_url='/login', autoescape=None, ) settings.update(options.as_dict()) self.db = db_session super(Application, self).__init__(handlers, **settings)
def main(): tornado.options.parse_command_line() rewrites = json.load(open(options.rewrite_json)) for userid, params in rewrites.items(): params['url'] = urlparse.urlparse(params.get('url')) ## ┏━┓┏━╸╺┳╸╺┳╸╻┏┓╻┏━╸┏━┓ ## ┗━┓┣╸ ┃ ┃ ┃┃┗┫┃╺┓┗━┓ ## ┗━┛┗━╸ ╹ ╹ ╹╹ ╹┗━┛┗━┛ handlers = [ tornado.web.url(r'/Microsoft-Server-ActiveSync.*', MicrosoftServerActiveSyncHandler), tornado.web.url(r'/__stub__$', StubHandler), ] settings = dict(rewrites=rewrites, compress_response=False, xsrf_cookies=False, **options.as_dict()) tornado.log.gen_log.debug(pprint.pformat(settings)) ## ┏━┓┏━┓┏━┓╻ ╻┏━╸┏━┓╺┳╸╻┏━┓┏┓╻ ## ┣━┫┣━┛┣━┛┃ ┃┃ ┣━┫ ┃ ┃┃ ┃┃┗┫ ## ╹ ╹╹ ╹ ┗━╸╹┗━╸╹ ╹ ╹ ╹┗━┛╹ ╹ application = tornado.web.Application(handlers=handlers, **settings) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) http_server.listen(options.listen_port, address=options.listen_host) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop_status = ioloop.start() except KeyboardInterrupt: ioloop_status = ioloop.stop() return ioloop_status
def main(config_file=None): # noinspection PyUnresolvedReferences import frontik.options parse_configs_and_start(config_files=config_file) if options.app is None: log.exception('no frontik application present (`app` option is not specified)') sys.exit(1) try: module = importlib.import_module(options.app) except Exception as e: log.exception('failed to import application module "%s": %s', options.app, e) sys.exit(1) if options.app_class is not None and not hasattr(module, options.app_class): log.exception('application class "%s" not found', options.app_class) sys.exit(1) application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication try: tornado_app = application(**options.as_dict()) ioloop = tornado.ioloop.IOLoop.instance() def _async_init_cb(): def _run_server_cb(future): if future.exception() is not None: log.exception('failed to start: %s', future.exception()) sys.exit(1) run_server(tornado_app) ioloop.add_future( tornado_app.init_async(), _run_server_cb ) ioloop.add_callback(_async_init_cb) ioloop.start() except: log.exception('failed to initialize frontik application, quitting') sys.exit(1)
def __init__(self, service): settings = dict(debug=True) settings.update(options.as_dict()) client = obelisk.ObeliskOfLightClient(service) self.obelisk_handler = obelisk_handler.ObeliskHandler(client) self.brc_handler = broadcast.BroadcastHandler() self.p2p = CryptoTransportLayer(config.get('p2p-port', 8889), config.get('external-ip', '127.0.0.1')) self.p2p.join_network(config.get('seeds', [])) self.json_chan_handler = jsonchan.JsonChanHandler(self.p2p) self.ticker_handler = ticker.TickerHandler() handlers = [ # /block/<block hash> (r"/block/([^/]*)(?:/)?", rest_handlers.BlockHeaderHandler), # /block/<block hash>/transactions (r"/block/([^/]*)/transactions(?:/)?", rest_handlers.BlockTransactionsHandler), # /tx/ (r"/tx(?:/)?", rest_handlers.TransactionPoolHandler), # /tx/<txid> (r"/tx/([^/]*)(?:/)?", rest_handlers.TransactionHandler), # /address/<address> (r"/address/([^/]*)(?:/)?", rest_handlers.AddressHistoryHandler), # /height (r"/height(?:/)?", rest_handlers.HeightHandler), # /height (r"/status(?:/)?", status.StatusHandler, {"app": self}), # / (r"/", QuerySocketHandler) ] tornado.web.Application.__init__(self, handlers, **settings)
def start(demo=False): if demo: # load demo options. it will escape config file. cookie_secret = common.hmacstr(common.randomstr(), common.randomstr()) args = [ sys.argv[0], "--debug", "--host=0.0.0.0", "--port=8080", "--base_url=/ssweb", "--service_name=shadowsocks", "--cookie_secret=" + cookie_secret, "--logging=debug" ] options.parse_command_line(args) else: # pre-parse the command line options. it will be over write by 'load # options from config file'. by then, it yet loaded. options.parse_command_line() if options.config is not None: # load options from specified config file if not os.path.isfile(options.config): err_("Can't find config file '%s'." % options.config) exit(1) else: config = common.load_config(options.config) if config is not None: info_("Load config from file '%s'." % options.config) args = [sys.argv[0]] for item in config: args += ["--%s=%s" % (item, config[item])] try: options.parse_command_line(args) except tornado.options.Error: err_("Error on config file option.") sys.exit(1) else: # load options from config file, if the file exists. config_file = common.find_config_file() if config_file is not None: config = common.load_config(config_file) if config is not None: info_("Load config from file '%s'." % config_file) args = [sys.argv[0]] for item in config: args += ["--%s=%s" % (item, config[item])] try: options.parse_command_line(args) except tornado.options.Error: err_("Error on config file option.") sys.exit(1) # load options from command line try: options.parse_command_line() except tornado.options.Error: err_("Error on command line option.") sys.exit(1) debug_("options: %s" % json.dumps(options.as_dict(), sort_keys=True)) logging.debug("options: %s" % json.dumps(options.as_dict(), sort_keys=True)) # load shadowsocks configuration ss_config_filename = common.find_shadowsocks_config_file() if ss_config_filename is None: err_("Can't find any shadowsocks config file. Are you sure there " "installed shadowsocks already?") exit(1) config = common.load_shadowsocks_config(ss_config_filename) info_("Loading shadowsocks config from file '%s'." % ss_config_filename) start_tornado(config, ss_config_filename)
def serve(): """Read configuration and start the server.""" global EMAIL_FROM, SMTP_SETTINGS jobstores = {'default': SQLAlchemyJobStore(url=JOBS_STORE)} scheduler = TornadoScheduler(jobstores=jobstores, timezone=pytz.utc) scheduler.start() define('port', default=3210, help='run on the given port', type=int) define('address', default='', help='bind the server at the given address', type=str) define('ssl_cert', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_cert.pem'), help='specify the SSL certificate to use for secure connections') define('ssl_key', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_key.pem'), help='specify the SSL private key to use for secure connections') define('admin-email', default='', help='email address of the site administrator', type=str) define('smtp-host', default='localhost', help='SMTP server address', type=str) define('smtp-port', default=0, help='SMTP server port', type=int) define('smtp-local-hostname', default=None, help='SMTP local hostname', type=str) define('smtp-use-ssl', default=False, help='Use SSL to connect to the SMTP server', type=bool) define('smtp-starttls', default=False, help='Use STARTTLS to connect to the SMTP server', type=bool) define('smtp-ssl-keyfile', default=None, help='SSL key file', type=str) define('smtp-ssl-certfile', default=None, help='SSL cert file', type=str) define('smtp-ssl-context', default=None, help='SSL context', type=str) define('debug', default=False, help='run in debug mode', type=bool) define('config', help='read configuration file', callback=lambda path: tornado.options.parse_config_file( path, final=False)) if not options.config and os.path.isfile(DEFAULT_CONF): tornado.options.parse_config_file(DEFAULT_CONF, final=False) tornado.options.parse_command_line() if options.admin_email: EMAIL_FROM = options.admin_email for key, value in options.as_dict().items(): if key.startswith('smtp-'): SMTP_SETTINGS[key] = value if options.debug: logger.setLevel(logging.DEBUG) ssl_options = {} if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert): ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key) init_params = dict(listen_port=options.port, logger=logger, ssl_options=ssl_options, scheduler=scheduler) git_init() _reset_schedules_path = r'schedules/reset' _schedule_run_path = r'schedules/(?P<id_>\d+)/run' _schedules_path = r'schedules/?(?P<id_>\d+)?' _history_path = r'schedules/?(?P<id_>\d+)/history' _diff_path = r'schedules/(?P<id_>\d+)/diff/(?P<commit_id>[0-9a-f]+)/?(?P<old_commit_id>[0-9a-f]+)?/?' application = tornado.web.Application([ (r'/api/%s' % _reset_schedules_path, ResetSchedulesHandler, init_params), (r'/api/v%s/%s' % (API_VERSION, _reset_schedules_path), ResetSchedulesHandler, init_params), (r'/api/%s' % _schedule_run_path, RunScheduleHandler, init_params), (r'/api/v%s/%s' % (API_VERSION, _schedule_run_path), RunScheduleHandler, init_params), (r'/api/%s' % _history_path, HistoryHandler, init_params), (r'/api/v%s/%s' % (API_VERSION, _history_path), HistoryHandler, init_params), (r'/api/%s' % _diff_path, DiffHandler, init_params), (r'/api/v%s/%s' % (API_VERSION, _diff_path), DiffHandler, init_params), (r'/api/%s' % _schedules_path, SchedulesHandler, init_params), (r'/api/v%s/%s' % (API_VERSION, _schedules_path), SchedulesHandler, init_params), (r'/?(.*)', TemplateHandler, init_params), ], static_path=os.path.join( os.path.dirname(__file__), 'dist/static'), template_path=os.path.join( os.path.dirname(__file__), 'dist/'), debug=options.debug) http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None) logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http', options.address if options.address else '127.0.0.1', options.port) http_server.listen(options.port, options.address) try: IOLoop.instance().start() except (KeyboardInterrupt, SystemExit): pass
def start(demo=False): if demo: # load demo options. it will escape config file. cookie_secret = common.hmacstr(common.randomstr(), common.randomstr()) args = [sys.argv[0], "--debug", "--host=0.0.0.0", "--port=8080", "--base_url=/ssweb", "--service_name=shadowsocks", "--cookie_secret=" + cookie_secret, "--logging=debug"] options.parse_command_line(args) else: # pre-parse the command line options. it will be over write by 'load # options from config file'. by then, it yet loaded. options.parse_command_line() if options.config is not None: # load options from specified config file if not os.path.isfile(options.config): err_("Can't find config file '%s'." % options.config) exit(1) else: config = common.load_config(options.config) if config is not None: info_("Load config from file '%s'." % options.config) args = [sys.argv[0]] for item in config: args += ["--%s=%s" % (item, config[item])] try: options.parse_command_line(args) except tornado.options.Error: err_("Error on config file option.") sys.exit(1) else: # load options from config file, if the file exists. config_file = common.find_config_file() if config_file is not None: config = common.load_config(config_file) if config is not None: info_("Load config from file '%s'." % config_file) args = [sys.argv[0]] for item in config: args += ["--%s=%s" % (item, config[item])] try: options.parse_command_line(args) except tornado.options.Error: err_("Error on config file option.") sys.exit(1) # load options from command line try: options.parse_command_line() except tornado.options.Error: err_("Error on command line option.") sys.exit(1) debug_("options: %s" % json.dumps(options.as_dict(), sort_keys=True)) logging.debug("options: %s" % json.dumps(options.as_dict(), sort_keys=True)) # load shadowsocks configuration ss_config_filename = common.find_shadowsocks_config_file() if ss_config_filename is None: err_("Can't find any shadowsocks config file. Are you sure there " "installed shadowsocks already?") exit(1) config = common.load_shadowsocks_config(ss_config_filename) info_("Loading shadowsocks config from file '%s'." % ss_config_filename) start_tornado(config, ss_config_filename)
def main(): tornado.options.parse_command_line() ## ┏━┓┏━╸╺┳╸╺┳╸╻┏┓╻┏━╸┏━┓ ## ┗━┓┣╸ ┃ ┃ ┃┃┗┫┃╺┓┗━┓ ## ┗━┛┗━╸ ╹ ╹ ╹╹ ╹┗━┛┗━┛ code_path = path.path(__file__).parent static_path = code_path.joinpath('static') template_path = code_path.joinpath('templates') support_path = code_path.joinpath('support') handlers = [ ## Static File Serving #tornado.web.url(r'/static/(css/.*)', tornado.web.StaticFileHandler, {'path': static_path}), #tornado.web.url(r'/static/(ico/.*)', tornado.web.StaticFileHandler, {'path': static_path}), #tornado.web.url(r'/static/(img/.*)', tornado.web.StaticFileHandler, {'path': static_path}), #tornado.web.url(r'/static/(js/.*)', tornado.web.StaticFileHandler, {'path': static_path}), ## Misc tornado.web.url(r'/__stub__$', StubHandler), ## FAQ tornado.web.url(r'/faq', FAQPageHandler, name='faq'), ## Status tornado.web.url(r'/status', StatusPageHandler, name='status'), ## IPv6 tornado.web.url(r'/ipv6', IPv6PageHandler, name='ipv6'), ## SSL tornado.web.url(r'/ssl', SSLPageHandler, name='ssl'), ## Donation tornado.web.url(r'/donation', DonationPageHandler, name='donation'), ## Subdomain Registration (form) tornado.web.url(r'/subdomain/registration', SubdomainRegistrationHandler, name='subdomain/registration'), tornado.web.url(r'/subdomain/registration/(.*)', SubdomainRegistrationHandler, name='subdomain/registration/encrypted_payload'), ## Subdomain Activation (encoded URL) tornado.web.url(r'/subdomain/activation/(.*)', SubdomainActivationHandler, name='subdomain/activation/encrypted_payload'), ## Home tornado.web.url(r'/', HomePageHandler, name='home'), ] motor_client = motor.MotorClient(options.mongodb_uri, tz_aware=True, read_preference=pymongo.read_preferences.ReadPreference.NEAREST) settings = dict( login_url = '/login', logout_url = '/logout', register_url = '/register', static_path = static_path, template_path = template_path, support_path = support_path, xsrf_cookies = True, motor_client = motor_client, **options.as_dict() ) tornado.log.gen_log.debug(pprint.pformat(settings)) ## ┏━┓┏━┓┏━┓╻ ╻┏━╸┏━┓╺┳╸╻┏━┓┏┓╻ ## ┣━┫┣━┛┣━┛┃ ┃┃ ┣━┫ ┃ ┃┃ ┃┃┗┫ ## ╹ ╹╹ ╹ ┗━╸╹┗━╸╹ ╹ ╹ ╹┗━┛╹ ╹ application = tornado.web.Application(handlers=handlers, **settings) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) http_server.listen(options.listen_port, address=options.listen_host) loop = tornado.ioloop.IOLoop.instance() try: loop_status = loop.start() except KeyboardInterrupt: loop_status = loop.stop() return loop_status
from tornado import ioloop, options import tornado from tornado.options import define, options, parse_command_line from TornadoProject import create_app # 定义 define(name="port", default="8888", help="port default 8888") if __name__ == '__main__': app = create_app() # 转换命令行参数 parse_command_line() # 选项调用 app.listen(options.port) print(options.as_dict()) tornado.ioloop.IOLoop.current().start()