class BokehServer(object): def listen(self, port): if self.server: return for i in range(5): try: self.server = Server(self.apps, io_loop=self.loop, port=port, check_unused_sessions_milliseconds=500, host=['*']) self.server.start(start_loop=False) break except (SystemExit, EnvironmentError): port = 0 if i == 4: raise @property def port(self): return (self.server.port or list(self.server._http._sockets.values())[0].getsockname()[1]) def stop(self): for context in self.server._tornado._applications.values(): context.run_unload_hook() self.server._tornado._stats_job.stop() self.server._tornado._cleanup_job.stop() if self.server._tornado._ping_job is not None: self.server._tornado._ping_job.stop()
def func(self, args): if args.port >= 0: self.port = args.port self.develop_mode = args.develop applications = self.build_applications(args) # TODO make log level a command line option logging.basicConfig(level=logging.DEBUG) server = Server(applications, port=self.port, address=args.address) if args.show: # we have to defer opening in browser until # we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) if self.develop_mode: log.info("Using develop mode (do not enable --develop in production)") address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info("Starting Bokeh server on port %d%s with applications at paths %r", server.port, address_string, sorted(applications.keys())) server.start()
def invoke(self, args): ''' ''' # protect this import inside a function so that "bokeh info" can work # even if Tornado is not installed from bokeh.server.server import Server log_level = getattr(logging, args.log_level.upper()) basicConfig(level=log_level, format=args.log_format) applications = {} _allowed_keys = ['port', 'address'] server_kwargs = { key: getattr(args, key) for key in _allowed_keys if getattr(args, key, None) is not None } with report_server_init_errors(**server_kwargs): server = Server(applications, **server_kwargs) address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info("Starting Bokeh static server on port %d%s", server.port, address_string) server.run_until_shutdown()
def invoke(self, args): applications = build_single_handler_applications(args.files) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level) if len(applications) == 0: # create an empty application by default, typically used with output_server applications['/'] = Application() server = Server(applications, port=args.port, address=args.address) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) if args.develop: log.info("Using develop mode (do not enable --develop in production)") address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info("Starting Bokeh server on port %d%s with applications at paths %r", server.port, address_string, sorted(applications.keys())) server.start()
def worker(): io_loop = IOLoop() server = Server({'/': modify_doc}, port=port, io_loop=io_loop, extra_patterns=[('/exit', _ExitHandler, dict(io_loop=io_loop))]) server.start() server.io_loop.start()
def run_server(filename, config=None, path='/', port=5000): """Run the bokeh server.""" if config is None: config = default_config(filename) makedoc = make_makedoc(filename, config) apps = {path: Application(FunctionHandler(makedoc))} server = Server(apps, port=port, allow_websocket_origin=['*']) server.run_until_shutdown()
class Bokeh_Worker(Thread): # Init thread running server def __init__(self, dev_app, trends_app, notes_app, serverIP, *, daemon=True): Thread.__init__(self, daemon=daemon) self._dev_app_ref = weakref.ref(dev_app) self._trends_app_ref = weakref.ref(trends_app) self._notes_app_ref = weakref.ref(notes_app) self.IP = serverIP self.exitFlag = False def run(self): self.process() def process(self): while not self.exitFlag: self.task() def startServer(self): self.server = Server( { "/devices": self._dev_app_ref(), "/trends": self._trends_app_ref(), "/notes": self._notes_app_ref(), }, io_loop=IOLoop(), allow_websocket_origin=[ "{}:8111".format(self.IP), "{}:5006".format(self.IP), "{}:8111".format("localhost"), "{}:5006".format("localhost"), ], ) self.server.start() self.server.io_loop.start() def task(self): try: self.startServer() except Exception as err: self._log.warning("Bokeh server already running", err) self.exitFlag = True def stop(self): self.bokeh_server.stop() self.exitFlag = True def beforeStop(self): """ Action done when closing thread """ pass
class ManagedServerLoop(object): def __init__(self, application): loop = IOLoop() loop.make_current() self._server = Server(application, io_loop=loop) def __exit__(self, type, value, traceback): self._server.unlisten() self._server.io_loop.close() def __enter__(self): return self._server @property def io_loop(self): return self.s_server.io_loop
def bk_worker(): # Can't pass num_procs > 1 in this configuration. If you need to run multiple # processes, see e.g. flask_gunicorn_embed.py server = Server({ '/spawns': spawnapp, '/tracks': tracksapp }, io_loop=IOLoop(), allow_websocket_origin=[ "127.0.0.1:8000", "localhost:5006", "localhost:8000" ]) server.start() server.io_loop.start()
def show_app(app, state, notebook_url, port=0, **kw): """Show Bokeh applications :param app: A Bokeh Application to embed in PyWebIO. :param state: ** Unused ** :param notebook_url: ** Unused ** :param port: Bokeh Server 端口 :param kw: 传给 Bokeh Server 的额外参数 """ from bokeh.server.server import Server from bokeh.io.notebook import _origin_url, uuid4, curstate, _server_url from pywebio.platform.tornado import ioloop loop = ioloop() loop.make_current() asyncio.set_event_loop(loop.asyncio_loop) # loop = IOLoop.current() info = get_info() allow_websocket_origin = [info.server_host] if info.origin: allow_websocket_origin.append(_origin_url(info.origin)) server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=allow_websocket_origin, **kw) server_id = uuid4().hex curstate().uuid_to_server[server_id] = server server.start() url = _server_url(info.server_host, server.port) from bokeh.embed import server_document script = server_document(url, resources=None) script = re.sub( r'<script(.*?)>([\s\S]*?)</script>', r""" <script \g<1>> requirejs(['bokeh', 'bokeh-widgets', 'bokeh-tables', 'bokeh-gl'], function(Bokeh) { \g<2> }); </script> """, script) put_html(script, sanitize=False)
def show(self, port=0, websocket_origin=None): """ Starts a bokeh server and displays the Viewable in a new tab Arguments --------- port: int (optional) Allows specifying a specific port (default=0 chooses random open port) websocket_origin: str or list(str) (optional) A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, "localhost" is used. Returns ------- server: bokeh Server instance """ def modify_doc(doc): return self.server_doc(doc) handler = FunctionHandler(modify_doc) app = Application(handler) from tornado.ioloop import IOLoop loop = IOLoop.current() if websocket_origin and not isinstance(websocket_origin, list): websocket_origin = [websocket_origin] opts = dict(allow_websocket_origin=websocket_origin) if websocket_origin else {} opts['io_loop'] = loop server = Server({'/': app}, port=port, **opts) def show_callback(): server.show('/') server.io_loop.add_callback(show_callback) server.start() def sig_exit(*args, **kwargs): loop.add_callback_from_signal(do_stop) def do_stop(*args, **kwargs): loop.stop() signal.signal(signal.SIGINT, sig_exit) try: loop.start() except RuntimeError: pass return server
def _bokeh_init(): io_loop = IOLoop.current() server = Server( { '/_measure': Application(ScriptHandler(filename='{}/palmar_grip.py'.format(MODELS_PATH))), '/_calibre': Application(ScriptHandler(filename='{}/calibration.py'.format(MODELS_PATH))), '/_plot' : Application(ScriptHandler(filename='{}/plot_measure.py'.format(MODELS_PATH))), }, io_loop=io_loop, allow_websocket_origin=["localhost:5000"] ) server.start() io_loop.start()
class ManagedServerLoop(object): def __init__(self, application, **server_kwargs): loop = IOLoop() loop.make_current() server_kwargs['io_loop'] = loop self._server = Server(application, **server_kwargs) def __exit__(self, type, value, traceback): self._server.unlisten() self._server.io_loop.close() def __enter__(self): return self._server @property def io_loop(self): return self.s_server.io_loop
def run_server(appname, path='.', filename='', gff_file=None, ref_file=None, bam_file=None, port=8000, **kwargs): if appname == 'test': app = dashboards.test_app() elif appname == 'align': app = dashboards.sequence_alignment_viewer(filename) elif appname == 'features': app = dashboards.genome_features_viewer(gff_file, ref_file) elif appname == 'bam': app = dashboards.bam_viewer(bam_file, ref_file, gff_file, width=1000) else: print('valid dashboard names: test, align, bam, features') return if app is None: print('please provide the correct input files') return from bokeh.server.server import Server def modify_doc(doc): return app.server_doc(doc=doc, title='pybioviz: %s' % appname) server = Server({'/': modify_doc}, port=port) print('Opening application on http://localhost:%s/' % server.port) server.start() server.show('/') server.run_until_shutdown() return
def bokehServer_worker(): server = Server( { '/' + TAT_app_url: TAT_app, '/' + QC_app_url: QC_app }, port=container_bokehServer_port, # following defines through which URLs the user is allowed to connect to these apps allow_websocket_origin=[ host_ip + ':' + str(host_dashboard_port), host_ip + ':' + str(host_bokehServer_port) ]) server.start() server.io_loop.start()
def main(): """Launch the server and connect to it.""" print("Preparing a bokeh application.") io_loop = IOLoop.current() bokeh_app = Application(FunctionHandler(modify_doc)) server = Server({"/": bokeh_app}, io_loop=io_loop, prefix="stream-debugger") server.start() print("Opening Bokeh application on http://localhost:5006/") io_loop.add_callback(server.show, "/") io_loop.start()
def start_dashboard(dashboard: Dashboard, args: argparse.Namespace) -> None: app = Application() app.add(dashboard) if args.dashboard_allow_websocket_origin: allow_websocket_origin = args.dashboard_allow_websocket_origin else: allow_websocket_origin = [ 'localhost:{}'.format(args.dashboard_port), '{}:{}'.format(args.external_hostname, args.dashboard_port) ] server = Server(app, port=args.dashboard_port, allow_websocket_origin=allow_websocket_origin) server.start()
def bk_worker(): # Can't pass num_procs > 1 in this configuration. # If you need to run multiple # processes, see e.g. flask_gunicorn_embed.py server = Server( { "/table": plotter.show_table, "/map": plotter.test_hist }, io_loop=IOLoop(), allow_websocket_origin=["localhost:5000"], ) server.start() server.io_loop.start()
def test_launch_simple_server(self): obj = Curve([]) launched = [] def modify_doc(doc): bokeh_renderer(obj, doc=doc) launched.append(True) server.stop() handler = FunctionHandler(modify_doc) app = Application(handler) server = Server({'/': app}, port=0) server.start() url = "http://localhost:" + str(server.port) + "/" pull_session(session_id='Test', url=url, io_loop=server.io_loop) self.assertTrue(len(launched)==1)
def startServer(self): self.server = Server( { '/devices': self._dev_app_ref(), '/trends': self._trends_app_ref(), '/notes': self._notes_app_ref() }, io_loop=IOLoop(), allow_websocket_origin=[ "{}:8111".format(self.IP), "{}:5006".format(self.IP), "{}:8111".format('localhost'), "{}:5006".format('localhost') ]) self.server.start() self.server.io_loop.start()
def bk_worker(): # Can't pass num_procs > 1 in this configuration. If you need to run multiple # processes, see e.g. flask_gunicorn_embed.py doc_functions = plugin_manager.getAllPlugins() doc_names = [_.name for _ in doc_functions] # create dictionary of the form {"/analysis1": doc_function1, "/analysis2": doc_function2} docs = {"/" + doc_names[j]: doc_functions[j].plugin_object.bkapp for j in range(len(doc_functions))} server = Server(docs, io_loop=IOLoop(), allow_websocket_origin=["localhost:5000", "127.0.0.1:5000"]) server.start() server.io_loop.start()
def run_server(self, *args, port: int = 5000, **kwargs): """Start the bokeh server with the experiment (*args and **kwargs are passed on to the Experiment.run() method). Keyword Arguments: port {int} -- the port to run the server on (default: {5000}) """ server = Server({"/": lambda doc: self.run(doc, *args, **kwargs)}, port=port, num_procs=1) server.start() print(f"Starting experiment at http://localhost:{port}/") server.io_loop.add_callback(server.show, "/") server.io_loop.start()
def bk_worker(): # Can't pass num_procs > 1 in this configuration. If you need to run multiple # processes, see e.g. flask_gunicorn_embed.py server = Server( {'/app': data_explorer_app}, io_loop=IOLoop(), unused_session_lifetime=7.2e6, # 4 hours in ms allow_websocket_origin=[ '127.0.0.1:5000', '127.0.0.1:8080', 'www.panoptes-data.net', ]) server.start() server.io_loop.start()
def serverWorker(): server = Server( { '/Weighted': application.Visualisations.Weighted, '/Grouped': application.Visualisations.Grouped, '/Adjacent': application.Visualisations.Adjacent, '/Hierarchical': application.Visualisations.Hierarchical }, # list of Bokeh applications io_loop=IOLoop(), # Tornado IOLoop allow_websocket_origin=["127.0.0.1:8000", "localhost:5006"]) # start timers and services and immediately return server.start() server.io_loop.start()
def bk_worker(): # server = Server({'/bkapp': modify_doc, '/test2': modify_doc2}, io_loop=IOLoop(), port=5006, allow_websocket_origin=['*']) # server = Server({'/bkapp': modify_doc}, io_loop=IOLoop(), port=5006, allow_websocket_origin=['*']) # kws = {'port': 5006, 'prefix': '/bkapp/test1', 'allow_websocket_origin': ['*']} # server = Server(modify_doc, io_loop=IOLoop(), **kws) kws = {'port': 5006, 'prefix': '/bkapp', 'allow_websocket_origin': ['*']} server = Server({ '/app1': modify_doc, '/app2': modify_doc2 }, io_loop=IOLoop(), **kws) server.start() server.io_loop.start()
def app(self_or_cls, plot, show=False, new_window=False, websocket_origin=None): """ Creates a bokeh app from a HoloViews object or plot. By default simply attaches the plot to bokeh's curdoc and returns the Document, if show option is supplied creates an Application instance and displays it either in a browser window or inline if notebook extension has been loaded. Using the new_window option the app may be displayed in a new browser tab once the notebook extension has been loaded. A websocket origin is required when launching from an existing tornado server (such as the notebook) and it is not on the default port ('localhost:8888'). """ renderer = self_or_cls.instance(mode='server') # If show=False and not in notebook context return document if not show and not self_or_cls.notebook_context: doc, _ = renderer(plot) return doc def modify_doc(doc): renderer(plot, doc=doc) handler = FunctionHandler(modify_doc) app = Application(handler) if not show: # If not showing and in notebook context return app return app elif self_or_cls.notebook_context and not new_window: # If in notebook, show=True and no new window requested # display app inline opts = dict(notebook_url=websocket_origin) if websocket_origin else {} return bkshow(app, **opts) # If app shown outside notebook or new_window requested # start server and open in new browser tab from tornado.ioloop import IOLoop loop = IOLoop.current() opts = dict(allow_websocket_origin=[websocket_origin]) if websocket_origin else {} opts['io_loop' if bokeh_version > '0.12.7' else 'loop'] = loop server = Server({'/': app}, port=0, **opts) def show_callback(): server.show('/') server.io_loop.add_callback(show_callback) server.start() try: loop.start() except RuntimeError: pass return server
def get(self, app): protocol = 'https' if self.get_argument( 'https', default='false').upper() == 'TRUE' else 'http' origin = self.get_argument('origin', default='localhost:{port}') prefix = self.get_argument('prefix', default='/') prefix = prefix + '/' if not prefix[-1] == '/' else prefix path = self._full_path(app) code = convert(path) app = Application( CodeHandler(source=code, filename='dynamic_notebook_convert')) loop = IOLoop.current() # TODO: Work this outsome how port = random.randint( 1024, 65535) # TODO: Should check if this is taken or not... origin = origin.replace("{port}", str(port)) prefix = prefix.replace("{port}", str(port)) server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=[ 'localhost:%d' % port, origin, self.request.host ]) # TODO: track and kill off servers? # server_id = uuid4().hex # curstate().uuid_to_server[server_id] = server server.start() orig_script = server_document( 'http://localhost:{port}/'.format(port=port), relative_urls=True) print(orig_script) ele_id = re.findall(r'\bid="([-A-z0-9]+)"', orig_script)[0] script = """<script src="{protocol}://{origin}{prefix}autoload.js?bokeh-autoload-element={ele_id}&bokeh-absolute-url={protocol}://{origin}&bokeh-app-path={prefix}" id="{ele_id}" data-bokeh-model-id="" data-bokeh-doc-id="" ></script>""".format(protocol=protocol, origin=origin, prefix=prefix, ele_id=ele_id) self.set_header('Content-Type', 'application/json') self.finish(json.dumps({'script': script}))
def listen(self, addr): if self.server: return if isinstance(addr, tuple): ip, port = addr else: port = addr ip = None for i in range(5): try: self.server = Server(self.apps, port=port, address=ip, check_unused_sessions_milliseconds=500, allow_websocket_origin=["*"], use_index=False, extra_patterns=[(r'/', web.RedirectHandler, { 'url': '/status' })], **self.server_kwargs) self.server.start() handlers = [(self.prefix + r'/statics/(.*)', web.StaticFileHandler, { 'path': os.path.join(os.path.dirname(__file__), 'static') })] self.server._tornado.add_handlers(r'.*', handlers) return except (SystemExit, EnvironmentError) as exc: if port != 0: if ("already in use" in str(exc) or # Unix/Mac "Only one usage of" in str(exc)): # Windows msg = ( "Port %d is already in use. " "\nPerhaps you already have a cluster running?" "\nHosting the diagnostics dashboard on a random port instead." % port) else: msg = "Failed to start diagnostics server on port %d. " % port + str( exc) warnings.warn('\n' + msg) port = 0 if i == 4: raise
def invoke(self, args): applications = build_single_handler_applications(args.files) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level) if len(applications) == 0: # create an empty application by default, typically used with output_server applications['/'] = Application() if args.keep_alive is not None: if args.keep_alive == 0: log.info("Keep-alive ping disabled") else: log.info("Keep-alive ping configured every %d milliseconds", args.keep_alive) # rename to be compatible with Server args.keep_alive_milliseconds = args.keep_alive server_kwargs = { key: getattr(args, key) for key in ['port', 'address', 'host', 'prefix', 'keep_alive_milliseconds'] if getattr(args, key, None) is not None } server = Server(applications, **server_kwargs) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) if args.develop: log.info( "Using develop mode (do not enable --develop in production)") address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info( "Starting Bokeh server on port %d%s with applications at paths %r", server.port, address_string, sorted(applications.keys())) server.start()
def launch_server(): maxlen = 1000000 # Initialize data carriers timetool = FakeTimetool() ipm = FakeBeam() timetool_d = deque(maxlen=maxlen) timetool_t = deque(maxlen=maxlen) ipm2_d = deque(maxlen=maxlen) ipm2_t = deque(maxlen=maxlen) ipm3_d = deque(maxlen=maxlen) ipm3_t = deque(maxlen=maxlen) timetool.fake_timetool.subscribe( partial(new_data, in_value=timetool_d, in_time=timetool_t)) ipm.fake_ipm2.subscribe(partial(new_data, in_value=ipm2_d, in_time=ipm2_t)) ipm.fake_ipm3.subscribe(partial(new_data, in_value=ipm3_d, in_time=ipm3_t)) origins = ["localhost:{}".format(5006)] server = Server( { '/Testing': partial(produce_graphs, timetool_d=timetool_d, timetool_t=timetool_t, ipm2_d=ipm2_d, ipm2_t=ipm2_t, ipm3_d=ipm3_d, ipm3_t=ipm3_t) }, allow_websocket_origin=origins, # num_procs must be 1 for tornado loops to work correctly num_procs=1, ) server.start() print('Opening Bokeh application on:') for entry in origins: print('\thttp://{}/'.format(entry)) try: server.io_loop.start() except KeyboardInterrupt: print("terminating") server.io_loop.stop()
def listen(self, port): if self.server: return for i in range(5): try: self.server = Server(self.apps, io_loop=self.loop, port=port, host=['*']) self.server.start(start_loop=False) break except (SystemExit, EnvironmentError): port = 0 if i == 4: raise
async def main(): print(f"Starting Tornado Server...") server = BokehServer({ "/": test_page }) # ioloop must remain to none, num_procs must be default (1) server.start() # Note : the bkapp is run for each request to the url... # bg clock task... asyncio.create_task(ticking()) print("Serving Bokeh application on http://localhost:5006/") await asyncio.sleep(3600) # running for one hour.
def launch_server(): try: apps = {"/analytics": Application(FunctionHandler(aion_analytics))} io_loop = IOLoop.current() server = Server(apps, port=5006, allow_websocket_origin=["*"], io_loop=io_loop, session_ids='signed', relative_urls=False) server.start() server.io_loop.add_callback(server.show, '/analytics') server.io_loop.start() except Exception: logger.error("WEBSERVER LAUNCH:", exc_info=True)
async def monosrv(applications: typing.Dict[str, typing.Callable[[Document], typing.Any]]): """ Async server runner, to force the eventloop -same as the server loop- to be already running...""" print(f"Starting Tornado Server...") # Server will take current running asyncio loop as his own. server = BokehServer(applications=applications, io_loop=None, num_procs=1) # ioloop must remain to none, num_procs must be default (1) # TODO : maybe better to explicitely set io_loop to current loop here... server.start() # TODO : how to handle exceptions here ?? # we would like to except, trigger some user-defined behavior and restart what needs to be. print("Serving DeBokeh application on http://localhost:5006/") await asyncio.sleep(3600) # running for one hour by default
def run_app(db, color_scheme): # thanks https://github.com/sqlalchemy/sqlalchemy/issues/4863 def connect(): return sqlite3.connect(f"file:{db}?mode=ro", uri=True) engine = create_engine("sqlite://", creator=connect) bkapp = AlgorithmScatter( DEFAULTS['x'], DEFAULTS['y'], engine=engine, cmap=palettes.get(color_scheme), ).plot().app server = Server({'/': bkapp}) server.start() server.io_loop.add_callback(server.show, "/") server.io_loop.start()
def msl(application: Application, port: int | None = None, **server_kwargs: Any) -> Iterator[Server]: if port is None: port = unused_tcp_port server = Server(application, port=port, **server_kwargs) server.start() yield server server.unlisten() server.stop()
def _run_server(fnc_make_document, iplot=True, notebook_url="localhost:8889", port=80): """Runs a Bokeh webserver application. Documents will be created using fnc_make_document""" handler = FunctionHandler(fnc_make_document) app = Application(handler) if iplot and 'ipykernel' in sys.modules: show(app, notebook_url=notebook_url) else: apps = {'/': app} print("Open your browser here: http://localhost") server = Server(apps, port=port) server.run_until_shutdown()
def main(): import sys from argparse import ArgumentParser parser = ArgumentParser(description='Princeton U19 DataJoint Interface') parser.add_argument('-p', '--port', type=int, default=5000, help='port for the bokeh server', action='store') parser.add_argument( '-n', '--num-proc', type=int, default=1, help='number of processes for the bokeh server (zero is auto)', action='store') parser.add_argument('-b', '--browser', default=False, action='store_true') ops = parser.parse_args() port = ops.port nproc = ops.num_proc browser = ops.browser import socket hostname = socket.gethostname() ipaddress = socket.gethostbyname(hostname) os.environ['BOKEH_ALLOW_WS_ORIGIN'] = 'localhost:{0},0.0.0.0:{0}'.format( port, hostname, ipaddress) os.environ['BOKEH_ALLOW_WS_ORIGIN'] = ','.join([ 'localhost:{0}', '0.0.0.0:{0}', '{1}:{0},{2}:{0}', '{1}.princeton.edu:{0}', 'braincogs01.pni.princeton.edu', 'braincogs01-test0.pni.princeton.edu', 'braincogs01-test1.pni.princeton.edu' ]).format(port, hostname, ipaddress) server = Server({'/': bkapp}, address='0.0.0.0', port=port, num_procs=nproc) server.start() print('Opening Bokeh application on http://localhost:{0}/'.format( server.port)) if browser: server.io_loop.add_callback(server.show, '/') else: server.io_loop.add_callback(server.show, '/', '') server.io_loop.start()
def func(self, args): if args.port >= 0: self.port = args.port self.develop_mode = args.develop applications = self.build_applications(args) # TODO make log level a command line option logging.basicConfig(level=logging.DEBUG) server = Server(applications, port=self.port) if self.develop_mode: log.info("Using develop mode (do not enable --develop in production)") log.info("Starting Bokeh server on port %d with apps at %r", server.port, sorted(applications.keys())) server.start()
def invoke(self, args): applications = build_single_handler_applications(args.files) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level) if len(applications) == 0: # create an empty application by default, typically used with output_server applications['/'] = Application() if args.keep_alive is not None: if args.keep_alive == 0: log.info("Keep-alive ping disabled") else: log.info("Keep-alive ping configured every %d milliseconds", args.keep_alive) # rename to be compatible with Server args.keep_alive_milliseconds = args.keep_alive server_kwargs = { key: getattr(args, key) for key in ['port', 'address', 'host', 'prefix', 'keep_alive_milliseconds'] if getattr(args, key, None) is not None } server = Server(applications, **server_kwargs) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) if args.develop: log.info("Using develop mode (do not enable --develop in production)") address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info("Starting Bokeh server on port %d%s with applications at paths %r", server.port, address_string, sorted(applications.keys())) server.start()
def invoke(self, args): log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level, format=args.log_format) applications = {} _allowed_keys = ['port', 'address'] server_kwargs = { key: getattr(args, key) for key in _allowed_keys if getattr(args, key, None) is not None } server = Server(applications, **server_kwargs) address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info("Starting Bokeh static server on port %d%s", server.port, address_string) server.start()
def finish(self): if not self.disable_server: def modify_doc(doc): doc.add_root(self.layout) doc.title = self.name directory = os.path.abspath(os.path.dirname(__file__)) theme_path = os.path.join(directory, "theme.yaml") template_path = os.path.join(directory, "templates") doc.theme = Theme(filename=theme_path) env = jinja2.Environment( loader=jinja2.FileSystemLoader(template_path) ) doc.template = env.get_template('index.html') self.log.info('Opening Bokeh application on ' 'http://localhost:{}/'.format(self.port)) server = Server({'/': modify_doc}, num_procs=1, port=self.port) server.start() server.io_loop.add_callback(server.show, "/") server.io_loop.start()
def listen(self, port): if self.server: return for i in range(5): try: self.server = Server(self.apps, io_loop=self.loop, port=port, check_unused_sessions_milliseconds=500, host=['*']) self.server.start(start_loop=False) break except (SystemExit, EnvironmentError): port = 0 if i == 4: raise
def startServer(self): self.server = Server( { "/devices": self._dev_app_ref(), "/trends": self._trends_app_ref(), "/notes": self._notes_app_ref(), }, io_loop=IOLoop(), allow_websocket_origin=[ "{}:8111".format(self.IP), "{}:5006".format(self.IP), "{}:8111".format("localhost"), "{}:5006".format("localhost"), ], ) self.server.start() self.server.io_loop.start()
def listen(self, addr): if self.server: return if isinstance(addr, tuple): ip, port = addr else: port = addr ip = None for i in range(5): try: self.server = Server(self.apps, port=port, address=ip, check_unused_sessions_milliseconds=500, allow_websocket_origin=["*"], use_index=False, extra_patterns=[(r'/', web.RedirectHandler, {'url': '/status'})], **self.server_kwargs) self.server.start() handlers = [(self.prefix + r'/statics/(.*)', web.StaticFileHandler, {'path': os.path.join(os.path.dirname(__file__), 'static')})] self.server._tornado.add_handlers(r'.*', handlers) return except (SystemExit, EnvironmentError) as exc: if port != 0: if ("already in use" in str(exc) or # Unix/Mac "Only one usage of" in str(exc)): # Windows msg = ("Port %d is already in use. " "\nPerhaps you already have a cluster running?" "\nHosting the diagnostics dashboard on a random port instead." % port) else: msg = "Failed to start diagnostics server on port %d. " % port + str(exc) warnings.warn('\n' + msg) port = 0 if i == 4: raise
class ManagedServerLoop(object): def __init__(self, application, **server_kwargs): loop = IOLoop() loop.make_current() server_kwargs['io_loop'] = loop self._server = Server(application, **server_kwargs) def __exit__(self, type, value, traceback): self._server.unlisten() self._server.stop() self._server.io_loop.close() def __enter__(self): self._server.start(start_loop=False) return self._server @property def io_loop(self): return self.s_server.io_loop
def invoke(self, args): applications = build_single_handler_applications(args.files) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level) if len(applications) == 0: # create an empty application by default, typically used with output_server applications['/'] = Application() if args.keep_alive is not None: if args.keep_alive == 0: log.info("Keep-alive ping disabled") else: log.info("Keep-alive ping configured every %d milliseconds", args.keep_alive) # rename to be compatible with Server args.keep_alive_milliseconds = args.keep_alive server_kwargs = { key: getattr(args, key) for key in ['port', 'address', 'allow_websocket_origin', 'host', 'prefix', 'develop', 'keep_alive_milliseconds', 'use_xheaders', ] if getattr(args, key, None) is not None } server_kwargs['sign_sessions'] = settings.sign_sessions() server_kwargs['secret_key'] = settings.secret_key_bytes() server_kwargs['generate_session_ids'] = True if args.session_ids is None: # no --session-ids means use the env vars pass elif args.session_ids == 'unsigned': server_kwargs['sign_sessions'] = False elif args.session_ids == 'signed': server_kwargs['sign_sessions'] = True elif args.session_ids == 'external-signed': server_kwargs['sign_sessions'] = True server_kwargs['generate_session_ids'] = False else: raise RuntimeError("argparse should have filtered out --session-ids mode " + args.session_ids) if server_kwargs['sign_sessions'] and not server_kwargs['secret_key']: die("To sign sessions, the BOKEH_SECRET_KEY environment variable must be set; " + "the `bokeh secret` command can be used to generate a new key.") server = Server(applications, **server_kwargs) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) if args.develop: log.info("Using develop mode (do not enable --develop in production)") address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info("Starting Bokeh server on port %d%s with applications at paths %r", server.port, address_string, sorted(applications.keys())) server.start()
def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource(data=data).data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) doc.add_root(column(slider, plot)) doc.theme = Theme(filename="theme.yaml") bokeh_app = Application(FunctionHandler(modify_doc)) # Setting num_procs here means we can't touch the IOLoop before now, we must # let Server handle that. If you need to explicitly handle IOLoops then you # will need to use the lower level BaseServer class. server = Server({'/bkapp': bokeh_app}, num_procs=4, extra_patterns=[('/', IndexHandler)]) server.start() if __name__ == '__main__': from bokeh.util.browser import view print('Opening Tornado app with embedded Bokeh application on http://localhost:5006/') server.io_loop.add_callback(view, "http://localhost:5006/") server.io_loop.start()
def invoke(self, args): applications = build_single_handler_applications(args.files) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level) if len(applications) == 0: # create an empty application by default, typically used with output_server applications["/"] = Application() if args.keep_alive is not None: if args.keep_alive == 0: log.info("Keep-alive ping disabled") else: log.info("Keep-alive ping configured every %d milliseconds", args.keep_alive) # rename to be compatible with Server args.keep_alive_milliseconds = args.keep_alive if args.check_unused_sessions is not None: log.info("Check for unused sessions every %d milliseconds", args.check_unused_sessions) # rename to be compatible with Server args.check_unused_sessions_milliseconds = args.check_unused_sessions if args.unused_session_lifetime is not None: log.info("Unused sessions last for %d milliseconds", args.unused_session_lifetime) # rename to be compatible with Server args.unused_session_lifetime_milliseconds = args.unused_session_lifetime if args.stats_log_frequency is not None: log.info("Log statistics every %d milliseconds", args.stats_log_frequency) # rename to be compatible with Server args.stats_log_frequency_milliseconds = args.stats_log_frequency server_kwargs = { key: getattr(args, key) for key in [ "port", "address", "allow_websocket_origin", "host", "prefix", "develop", "keep_alive_milliseconds", "check_unused_sessions_milliseconds", "unused_session_lifetime_milliseconds", "stats_log_frequency_milliseconds", "use_xheaders", ] if getattr(args, key, None) is not None } server_kwargs["sign_sessions"] = settings.sign_sessions() server_kwargs["secret_key"] = settings.secret_key_bytes() server_kwargs["generate_session_ids"] = True if args.session_ids is None: # no --session-ids means use the env vars pass elif args.session_ids == "unsigned": server_kwargs["sign_sessions"] = False elif args.session_ids == "signed": server_kwargs["sign_sessions"] = True elif args.session_ids == "external-signed": server_kwargs["sign_sessions"] = True server_kwargs["generate_session_ids"] = False else: raise RuntimeError("argparse should have filtered out --session-ids mode " + args.session_ids) if server_kwargs["sign_sessions"] and not server_kwargs["secret_key"]: die( "To sign sessions, the BOKEH_SECRET_KEY environment variable must be set; " + "the `bokeh secret` command can be used to generate a new key." ) server = Server(applications, **server_kwargs) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) if args.develop: log.info("Using develop mode (do not enable --develop in production)") address_string = "" if server.address is not None and server.address != "": address_string = " address " + server.address log.info( "Starting Bokeh server on port %d%s with applications at paths %r", server.port, address_string, sorted(applications.keys()), ) server.start()
def __init__(self, application): loop = IOLoop() loop.make_current() self._server = Server(application, io_loop=loop)
def bk_worker(): # Can't pass num_procs > 1 in this configuration. If you need to run multiple # processes, see e.g. flask_gunicorn_embed.py server = Server({'/bkapp': modify_doc}, allow_websocket_origin=["localhost:8000"]) server.start() server.io_loop.start()
def invoke(self, args): ''' ''' # protect this import inside a function so that "bokeh info" can work # even if Tornado is not installed from bokeh.server.server import Server argvs = { f : args.args for f in args.files} applications = build_single_handler_applications(args.files, argvs) log_level = getattr(logging, args.log_level.upper()) basicConfig(level=log_level, format=args.log_format, filename=args.log_file) if len(applications) == 0: # create an empty application by default applications['/'] = Application() # rename args to be compatible with Server if args.keep_alive is not None: args.keep_alive_milliseconds = args.keep_alive if args.check_unused_sessions is not None: args.check_unused_sessions_milliseconds = args.check_unused_sessions if args.unused_session_lifetime is not None: args.unused_session_lifetime_milliseconds = args.unused_session_lifetime if args.stats_log_frequency is not None: args.stats_log_frequency_milliseconds = args.stats_log_frequency if args.mem_log_frequency is not None: args.mem_log_frequency_milliseconds = args.mem_log_frequency server_kwargs = { key: getattr(args, key) for key in ['port', 'address', 'allow_websocket_origin', 'num_procs', 'prefix', 'keep_alive_milliseconds', 'check_unused_sessions_milliseconds', 'unused_session_lifetime_milliseconds', 'stats_log_frequency_milliseconds', 'mem_log_frequency_milliseconds', 'use_xheaders', 'websocket_max_message_size', ] if getattr(args, key, None) is not None } server_kwargs['sign_sessions'] = settings.sign_sessions() server_kwargs['secret_key'] = settings.secret_key_bytes() server_kwargs['generate_session_ids'] = True if args.session_ids is None: # no --session-ids means use the env vars pass elif args.session_ids == 'unsigned': server_kwargs['sign_sessions'] = False elif args.session_ids == 'signed': server_kwargs['sign_sessions'] = True elif args.session_ids == 'external-signed': server_kwargs['sign_sessions'] = True server_kwargs['generate_session_ids'] = False else: raise RuntimeError("argparse should have filtered out --session-ids mode " + args.session_ids) if server_kwargs['sign_sessions'] and not server_kwargs['secret_key']: die("To sign sessions, the BOKEH_SECRET_KEY environment variable must be set; " + "the `bokeh secret` command can be used to generate a new key.") server_kwargs['use_index'] = not args.disable_index server_kwargs['redirect_root'] = not args.disable_index_redirect with report_server_init_errors(**server_kwargs): server = Server(applications, **server_kwargs) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) address_string = 'localhost' if server.address is not None and server.address != '': address_string = server.address for route in sorted(applications.keys()): url = "http://%s:%d%s%s" % (address_string, server.port, server.prefix, route) log.info("Bokeh app running at: %s" % url) log.info("Starting Bokeh server with process id: %d" % getpid()) server.run_until_shutdown()
def app(self_or_cls, plot, show=False, new_window=False, websocket_origin=None, port=0): """ Creates a bokeh app from a HoloViews object or plot. By default simply attaches the plot to bokeh's curdoc and returns the Document, if show option is supplied creates an Application instance and displays it either in a browser window or inline if notebook extension has been loaded. Using the new_window option the app may be displayed in a new browser tab once the notebook extension has been loaded. A websocket origin is required when launching from an existing tornado server (such as the notebook) and it is not on the default port ('localhost:8888'). """ if not isinstance(self_or_cls, BokehRenderer) or self_or_cls.mode != 'server': renderer = self_or_cls.instance(mode='server') else: renderer = self_or_cls def modify_doc(doc): renderer(plot, doc=doc) handler = FunctionHandler(modify_doc) app = Application(handler) if not show: # If not showing and in notebook context return app return app elif self_or_cls.notebook_context and not new_window: # If in notebook, show=True and no new window requested # display app inline if isinstance(websocket_origin, list): if len(websocket_origin) > 1: raise ValueError('In the notebook only a single websocket origin ' 'may be defined, which must match the URL of the ' 'notebook server.') websocket_origin = websocket_origin[0] opts = dict(notebook_url=websocket_origin) if websocket_origin else {} return bkshow(app, **opts) # If app shown outside notebook or new_window requested # start server and open in new browser tab from tornado.ioloop import IOLoop loop = IOLoop.current() if websocket_origin and not isinstance(websocket_origin, list): websocket_origin = [websocket_origin] opts = dict(allow_websocket_origin=websocket_origin) if websocket_origin else {} opts['io_loop'] = loop server = Server({'/': app}, port=port, **opts) def show_callback(): server.show('/') server.io_loop.add_callback(show_callback) server.start() def sig_exit(*args, **kwargs): loop.add_callback_from_signal(do_stop) def do_stop(*args, **kwargs): loop.stop() signal.signal(signal.SIGINT, sig_exit) try: loop.start() except RuntimeError: pass return server
class BokehServer(object): server_kwargs = {} def listen(self, addr): if self.server: return if isinstance(addr, tuple): ip, port = addr else: port = addr ip = None for i in range(5): try: self.server = Server(self.apps, port=port, address=ip, check_unused_sessions_milliseconds=500, allow_websocket_origin=["*"], use_index=False, extra_patterns=[(r'/', web.RedirectHandler, {'url': '/status'})], **self.server_kwargs) self.server.start() handlers = [(self.prefix + r'/statics/(.*)', web.StaticFileHandler, {'path': os.path.join(os.path.dirname(__file__), 'static')})] self.server._tornado.add_handlers(r'.*', handlers) return except (SystemExit, EnvironmentError) as exc: if port != 0: if ("already in use" in str(exc) or # Unix/Mac "Only one usage of" in str(exc)): # Windows msg = ("Port %d is already in use. " "\nPerhaps you already have a cluster running?" "\nHosting the diagnostics dashboard on a random port instead." % port) else: msg = "Failed to start diagnostics server on port %d. " % port + str(exc) warnings.warn('\n' + msg) port = 0 if i == 4: raise @property def port(self): return (self.server.port or list(self.server._http._sockets.values())[0].getsockname()[1]) def stop(self): for context in self.server._tornado._applications.values(): context.run_unload_hook() self.server._tornado._stats_job.stop() self.server._tornado._cleanup_job.stop() if self.server._tornado._ping_job is not None: self.server._tornado._ping_job.stop() # https://github.com/bokeh/bokeh/issues/5494 if LooseVersion(bokeh.__version__) >= '0.12.4': self.server.stop()
def invoke(self, args): argvs = { f : args.args for f in args.files} applications = build_single_handler_applications(args.files, argvs) log_level = getattr(logging, args.log_level.upper()) logging.basicConfig(level=log_level, format=args.log_format) if len(applications) == 0: # create an empty application by default, typically used with output_server applications['/'] = Application() if args.keep_alive is not None: if args.keep_alive == 0: log.info("Keep-alive ping disabled") else: log.info("Keep-alive ping configured every %d milliseconds", args.keep_alive) # rename to be compatible with Server args.keep_alive_milliseconds = args.keep_alive if args.check_unused_sessions is not None: log.info("Check for unused sessions every %d milliseconds", args.check_unused_sessions) # rename to be compatible with Server args.check_unused_sessions_milliseconds = args.check_unused_sessions if args.unused_session_lifetime is not None: log.info("Unused sessions last for %d milliseconds", args.unused_session_lifetime) # rename to be compatible with Server args.unused_session_lifetime_milliseconds = args.unused_session_lifetime if args.stats_log_frequency is not None: log.info("Log statistics every %d milliseconds", args.stats_log_frequency) # rename to be compatible with Server args.stats_log_frequency_milliseconds = args.stats_log_frequency server_kwargs = { key: getattr(args, key) for key in ['port', 'address', 'allow_websocket_origin', 'host', 'num_procs', 'prefix', 'develop', 'keep_alive_milliseconds', 'check_unused_sessions_milliseconds', 'unused_session_lifetime_milliseconds', 'stats_log_frequency_milliseconds', 'use_xheaders', ] if getattr(args, key, None) is not None } server_kwargs['sign_sessions'] = settings.sign_sessions() server_kwargs['secret_key'] = settings.secret_key_bytes() server_kwargs['generate_session_ids'] = True if args.session_ids is None: # no --session-ids means use the env vars pass elif args.session_ids == 'unsigned': server_kwargs['sign_sessions'] = False elif args.session_ids == 'signed': server_kwargs['sign_sessions'] = True elif args.session_ids == 'external-signed': server_kwargs['sign_sessions'] = True server_kwargs['generate_session_ids'] = False else: raise RuntimeError("argparse should have filtered out --session-ids mode " + args.session_ids) if server_kwargs['sign_sessions'] and not server_kwargs['secret_key']: die("To sign sessions, the BOKEH_SECRET_KEY environment variable must be set; " + "the `bokeh secret` command can be used to generate a new key.") server_kwargs['use_index'] = not args.disable_index server_kwargs['redirect_root'] = not args.disable_index_redirect server = Server(applications, **server_kwargs) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) if args.develop: log.info("Using develop mode (do not enable --develop in production)") address_string = '' if server.address is not None and server.address != '': address_string = ' address ' + server.address log.info("Starting Bokeh server on port %d%s with applications at paths %r", server.port, address_string, sorted(applications.keys())) log.info("Starting Bokeh server with process id: %d" % getpid()) event_handler = LoggingEventHandler() observer = Observer() path = r'C:\Users\jhu\Desktop' observer.schedule(event_handler, path, recursive=False) observer.start() server.start()
def __init__(self, application, **server_kwargs): loop = IOLoop() loop.make_current() server_kwargs['io_loop'] = loop self._server = Server(application, **server_kwargs)
def invoke(self, args): ''' ''' # protect this import inside a function so that "bokeh info" can work # even if Tornado is not installed from bokeh.server.server import Server argvs = { f : args.args for f in args.files} applications = build_single_handler_applications(args.files, argvs) log_level = getattr(logging, args.log_level.upper()) basicConfig(level=log_level, format=args.log_format, filename=args.log_file) if len(applications) == 0: # create an empty application by default applications['/'] = Application() # rename args to be compatible with Server if args.keep_alive is not None: args.keep_alive_milliseconds = args.keep_alive if args.check_unused_sessions is not None: args.check_unused_sessions_milliseconds = args.check_unused_sessions if args.unused_session_lifetime is not None: args.unused_session_lifetime_milliseconds = args.unused_session_lifetime if args.stats_log_frequency is not None: args.stats_log_frequency_milliseconds = args.stats_log_frequency if args.mem_log_frequency is not None: args.mem_log_frequency_milliseconds = args.mem_log_frequency server_kwargs = { key: getattr(args, key) for key in ['port', 'address', 'allow_websocket_origin', 'num_procs', 'prefix', 'keep_alive_milliseconds', 'check_unused_sessions_milliseconds', 'unused_session_lifetime_milliseconds', 'stats_log_frequency_milliseconds', 'mem_log_frequency_milliseconds', 'use_xheaders', 'websocket_max_message_size', ] if getattr(args, key, None) is not None } server_kwargs['sign_sessions'] = settings.sign_sessions() server_kwargs['secret_key'] = settings.secret_key_bytes() server_kwargs['generate_session_ids'] = True if args.session_ids is None: # no --session-ids means use the env vars pass elif args.session_ids == 'unsigned': server_kwargs['sign_sessions'] = False elif args.session_ids == 'signed': server_kwargs['sign_sessions'] = True elif args.session_ids == 'external-signed': server_kwargs['sign_sessions'] = True server_kwargs['generate_session_ids'] = False else: raise RuntimeError("argparse should have filtered out --session-ids mode " + args.session_ids) if server_kwargs['sign_sessions'] and not server_kwargs['secret_key']: die("To sign sessions, the BOKEH_SECRET_KEY environment variable must be set; " + "the `bokeh secret` command can be used to generate a new key.") server_kwargs['use_index'] = not args.disable_index server_kwargs['redirect_root'] = not args.disable_index_redirect server_kwargs['autoreload'] = args.dev is not None def find_autoreload_targets(app_path): path = os.path.abspath(app_path) if not os.path.isdir(path): return for path, subdirs, files in os.walk(path): for name in files: if (fnmatch(name, '*.html') or fnmatch(name, '*.css') or fnmatch(name, '*.yaml')): log.info("Watching: " + os.path.join(path, name)) watch(os.path.join(path, name)) def add_optional_autoreload_files(file_list): for filen in file_list: if os.path.isdir(filen): log.warning("Cannot watch directory " + filen) continue log.info("Watching: " + filen) watch(filen) if server_kwargs['autoreload']: if len(applications.keys()) != 1: die("--dev can only support a single app.") if server_kwargs['num_procs'] != 1: log.info("Running in --dev mode. --num-procs is limited to 1.") server_kwargs['num_procs'] = 1 find_autoreload_targets(args.files[0]) add_optional_autoreload_files(args.dev) with report_server_init_errors(**server_kwargs): server = Server(applications, **server_kwargs) if args.show: # we have to defer opening in browser until we start up the server def show_callback(): for route in applications.keys(): server.show(route) server.io_loop.add_callback(show_callback) address_string = 'localhost' if server.address is not None and server.address != '': address_string = server.address for route in sorted(applications.keys()): url = "http://%s:%d%s%s" % (address_string, server.port, server.prefix, route) log.info("Bokeh app running at: %s" % url) log.info("Starting Bokeh server with process id: %d" % os.getpid()) server.run_until_shutdown()