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 run_bokeh_server(bok_io_loop): ##turn file paths into bokeh apps apps = build_single_handler_applications(files,argvs) ##args lifted from bokeh serve call to Server, with the addition of my own io_loop kwags = { 'io_loop':bok_io_loop, 'generade_session_ids':True, 'redirect_root':True, 'use_x_headers':False, 'secret_key':None, 'num_procs':1, 'host':['%s:%d'%(host,app_port),'%s:%d'%(host,bokeh_port)], 'sign_sessions':False, 'develop':False, 'port':bokeh_port, 'use_index':True } srv = Server(apps,**kwags)
def run(port, ip, debug, allow_websocket_origin, command): if debug: print('Setting debug') app = make_app(command, debug) server_kwargs = {'port': port, 'ip': ip} if allow_websocket_origin: server_kwargs['allow_websocket_origin'] = list(allow_websocket_origin) server = Server({ '/': app, '/ready-check': create_ready_app() }, **server_kwargs) server.run_until_shutdown()
def test_launch_server_with_complex_plot(self): dmap = DynamicMap(lambda x_range, y_range: Curve([]), streams=[RangeXY()]) overlay = dmap * HLine(0) static = Polygons([]) * Path([]) * Curve([]) layout = overlay + static launched = [] def modify_doc(doc): bokeh_renderer(layout, 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 serve_bokeh_tags(hdfstore): projectsPath = Path.home() / '.nestor-tmp' projectsPath.mkdir(parents=True, exist_ok=True) # nestorPath = Path(__file__).parent.parent # databaseToCsv_mapping = openYAMLConfig_File( # yaml_path=nestorPath / 'store_data' / 'csvHeader.yaml' # ) # names = load_header_mapping() # tech = names['technician']['name'] # mach = names['machine']['name'] tagplot = TagPlot(hdfstore, cat_specifier='name', topn=10) renderer = hv.renderer('bokeh').instance(mode='server') server = Server({ **{ '/' + urllib.parse.quote_plus(name)+'.bars': renderer.app(tagplot.hv_bars(name).options(width=900)) for name in tagplot.names }, **{ '/' + urllib.parse.quote_plus(name)+'.node': renderer.app(tagplot.hv_nodelink(name).options(width=900)) for name in tagplot.names }, **{ '/' + urllib.parse.quote_plus(name)+'.flow': renderer.app(tagplot.hv_flow(name).options(width=900)) for name in tagplot.names } }, port=5006, allow_websocket_origin=[ "127.0.0.1:5000", "localhost:5000", "localhost:5006", "0.0.0.0:5000", "0.0.0.0:5006" ]) server.start() # server.show('/') loop = IOLoop.current() loop.start()
def start_server(port): # 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. loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) app = App() context = zmq.asyncio.Context() socket = context.socket(zmq.REQ) socket.connect(f"tcp://127.0.0.1:{port}") app.socket = socket server = Server({'/': app.transform}, num_procs=1) server.start() #server.io_loop.add_callback(server.show, "/") server.io_loop.start()
def main(): FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(format=FORMAT, level=logging.DEBUG) server = Server( applications={ '/test_ConsoleView': test_ConsoleView, '/test_LoadFileView': test_LoadFileView, '/test_FigureViewController': test_FigureViewController, '/v0': v0, '/traces': traces, '/frqdiff': frqdiff, }, extra_patterns=[('/static/js/worker.js', StaticHandler, { "path": './static/js/worker.js' })], ) server.start() server.io_loop.start() pass
def __init__(self, rti_config, plot_manager=None): self.rti_config = rti_config # Bokeh App # Created when the server is created self.bokeh_app = None # Create the plot manager # This handles all the incoming data and pass it to the plots if plot_manager: self.plot_manager = plot_manager else: self.plot_manager = RtiBokehPlotManager(rti_config) self.plot_manager.start() # Create an app object by setting the path of the bokeh plot in the webserver # and setting the function to call to create a plot webpage apps = {'/': self.get_bokeh_app()} # Create the Bokeh server with the given port and IP address # The configuration has the local IP address. If you share the config # file, you must delete the IP line so the configuration will regenerate the # configuration file with a new IP line which is the local computers IP address bokeh_port = int(self.rti_config.config['PLOT']['PORT']) bokeh_ip = self.rti_config.config['PLOT']['IP'] websocket_allow = bokeh_ip + ":" + str(bokeh_port) self.server = Server(apps, port=bokeh_port, address=bokeh_ip, allow_websocket_origin=[websocket_allow]) self.server.start() # Only display the webpage if enabled if self.rti_config.config.getboolean('PLOT', 'LIVE'): self.server.show('/') # Outside the notebook ioloop needs to be started # Start the loop in a thread so it does not block loop = IOLoop.current() #loop.start() t = Thread(target=loop.start, daemon=True) t.start()
def _run_server(fnc_make_document, iplot=True, notebook_url="localhost:8889", port=80, ioloop=None): """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(f"Browser is launching at: http://localhost:{port}") threading.Timer(2, lambda: webbrowser.open(f'http://localhost:{port}')).start() server = Server(apps, port=port, io_loop=ioloop) if ioloop is None: server.run_until_shutdown() else: server.start() ioloop.start()
def start(self, update_cb): """ Start the rendering of the Board Args: update_cb (function(lib_inst)): called when the Rendering is refreshing """ self._update_cb = update_cb self._io_loop = IOLoop.current() #self._application = Application(CustomHandler(self, self._init_doc), FunctionHandler(self._modify_doc)) self._application = Application(CustomHandler(self, self._init_doc)) self._server = Server({'/' + self._name: self._application}, io_loop=self._io_loop, check_unused_sessions_milliseconds=1000, unused_session_lifetime_milliseconds=1000) self._server.start() self._io_loop.start()
def __spawn_server(self): bslg = logging.getLogger('bokeh.server.util') bsll = bslg.getEffectiveLevel() bslg.setLevel(logging.ERROR) self._server_info['application'] = app = Application( FunctionHandler(self.__entry_point)) self._server_info['server'] = srv = Server( {'/': app}, io_loop=IOLoop.instance(), port=0, allow_websocket_origin=['*']) self._server_info['server_id'] = srv_id = uuid4().hex curstate().uuid_to_server[srv_id] = srv srv_addr = srv.address if srv.address else socket.gethostbyname( socket.gethostname()) self._server_info['server_url'] = 'http://{}:{}/'.format( srv_addr, srv.port) srv.start() bslg.setLevel(bsll)
async def __post_create__(self): static_path = os.path.join(os.path.dirname(__file__), 'static') supervisor_addr = self.address host = self._config.get('host') or '0.0.0.0' port = self._config.get('port') or get_next_port() self._web_address = f'http://{host}:{port}' bokeh_apps = self._config.get('bokeh_apps', {}) web_handlers = self._config.get('web_handlers', {}) handlers = dict() for p, h in bokeh_apps.items(): handlers[p] = Application(FunctionHandler( functools.partial(h, supervisor_addr=supervisor_addr))) handler_kwargs = {'supervisor_addr': supervisor_addr} extra_patterns = [ (r'[^\?\&]*/static/(.*)', BokehStaticFileHandler, {'path': static_path}) ] for p, h in web_handlers.items(): extra_patterns.append((p, h, handler_kwargs)) retrial = 5 while retrial: try: if port is None: port = get_next_port() self._web_server = Server( handlers, allow_websocket_origin=['*'], address=host, port=port, extra_patterns=extra_patterns, http_server_kwargs={'max_buffer_size': 2 ** 32}, ) self._web_server.start() logger.info('Mars Web started at %s:%d', host, port) break except OSError: # pragma: no cover if port is not None: raise retrial -= 1 if retrial == 0: raise
def run(cls, argv=None, port=5006): if argv is None: argv = sys.argv[1:] parser = argparse.ArgumentParser(description=cls.short_desc()) parser.add_argument('input', nargs="?", help="Input file", type=str) parser.add_argument('--example', help="Print example input file", default=False, action="store_true") parser.add_argument('--desc', help="Print extended usage description", default=False, action="store_true") args = parser.parse_args(argv) if args.desc: print(cls.long_desc()) print('') print("casm plot " + cls.name() + " 'style' example:") print(json.dumps(cls.style_example(), indent=2)) return elif args.example: print(json.dumps(cls.input_example(), indent=2)) return elif args.input is not None: def f(doc): cls.plot(doc, args) server = Server({'/': f}, num_procs=1, port=port) server.start() print('Opening on http://localhost:' + str(port) + '/') print('Enter Ctrl+C to stop') try: server.io_loop.add_callback(server.show, "/") server.io_loop.start() except KeyboardInterrupt as e: print('\nStopping...') pass else: parser.print_help() return
def configServer(): """ """ # LOOP OVER THE CONFIG TO MAKE THIS ldtWeatherFunc = FunctionHandler(ldtWeather.make_plot) ldtWeatherApp = Application(ldtWeatherFunc) ldtWeatherTableFunc = FunctionHandler(ldtWeatherTable.makeTable) ldtWeatherTableApp = Application(ldtWeatherTableFunc) ldtWindFunc = FunctionHandler(ldtWind.make_plot) ldtWindApp = Application(ldtWindFunc) ldtWindTableFunc = FunctionHandler(ldtWindTable.makeTable) ldtWindTableApp = Application(ldtWindTableFunc) facsumTCSFunc = FunctionHandler(facsumTCS.makeFacSum) facsumTCSApp = Application(facsumTCSFunc) facsumLPIFunc = FunctionHandler(facsumLPI.makeFacSum) facsumLPIApp = Application(facsumLPIFunc) apps = { '/ldtweather': ldtWeatherApp, '/ldtweathertable': ldtWeatherTableApp, '/ldtwind': ldtWindApp, '/ldtwindtable': ldtWindTableApp, '/facsum_tcs': facsumTCSApp, '/facsum_lpi': facsumLPIApp } print("Starting bokeh server...") server = Server(apps, port=5000, allow_websocket_origin=[ '127.0.0.1:8000', '127.0.0.1:5000', 'localhost:5000', 'localhost:8000', 'dctsleeperservice:5000', 'dctsleeperservice:9876', 'nightwatch', 'nightwatch.lowell.edu' ]) return server
def start_server(): script_path = os.path.join(os.path.dirname(__file__), 'data') css_path = os.path.join(os.path.dirname(__file__), 'static/css') extra_patterns = [(r"/data/(.*)", tornado.web.StaticFileHandler, { "path": script_path }), (r"/css/(.*)", tornado.web.StaticFileHandler, { "path": css_path }), (r"/fonts/(.*)", tornado.web.StaticFileHandler, { "path": 'fonts' }), (r"/", IndexHandler)] bokeh_apps = dict() module_dict = GenericHandler.get_all_urls() #set the extra patter and the bokeh applications based on the module config.xmls urls = module_dict['urls'] print(module_dict) for i, ival in enumerate(urls): if module_dict['types'][i] == 'tornado': extra_patterns.append( (r"/" + ival, GenericHandler, dict(key=ival))) for child in module_dict['children'][i]: extra_patterns.append( (r"/" + child, GenericHandler, dict(key=child))) elif module_dict['types'][i] == 'bokeh': function_handler = GenericHandler.get_function_handler_for_bokeh( GenericHandler, ival) bokeh_app = bokeh.application.Application(function_handler) bokeh_apps['/' + ival] = bokeh_app for child in module_dict['children'][i]: function_handler = GenericHandler.get_function_handler_for_bokeh( GenericHandler, child) bokeh_app = bokeh.application.Application(function_handler) bokeh_apps['/' + child] = bokeh_app server = Server(bokeh_apps, num_procs=1, extra_patterns=extra_patterns) server.start() return server
def _try_start_web_server(self): static_path = os.path.join(os.path.dirname(__file__), 'static') handlers = dict() for p, h in _bokeh_apps.items(): handlers[p] = Application( FunctionHandler( functools.partial(h, scheduler_ip=self._scheduler_ip))) handler_kwargs = {'scheduler_ip': self._scheduler_ip} extra_patterns = [('/static/(.*)', BokehStaticFileHandler, { 'path': static_path })] for p, h in _web_handlers.items(): extra_patterns.append((p, h, handler_kwargs)) retrial = 5 while retrial: try: if self._port is None: use_port = get_next_port() else: use_port = self._port self._server = Server( handlers, allow_websocket_origin=['*'], address=self._host, port=use_port, extra_patterns=extra_patterns, http_server_kwargs={'max_buffer_size': 2**32}, ) self._server.start() self._port = use_port logger.info('Mars UI started at %s:%d', self._host, self._port) break except OSError: if self._port is not None: raise retrial -= 1 if retrial == 0: raise
def start_server(address, port, url, attempts=100): while attempts: attempts -= 1 try: server = Server( {url: graph_it}, num_procs=1, port=port, address=address, allow_websocket_origin=[f"{address}:{port}",], ) server.start() return server, port except OSError as ex: if "Address already in use" in str(ex): print(f"Port {port} busy") port += 1 else: raise ex raise Exception("Failed to find available port")
def _show_zeppelin_app_with_state(app, state, notebook_url): logging.basicConfig() from tornado.ioloop import IOLoop from bokeh.server.server import Server loop = IOLoop.current() server = Server({"/": app}, io_loop=loop, port=0, allow_websocket_origin=[notebook_url]) server_id = uuid.uuid4().hex if _isAfterBokeh1210: from bokeh.io.state import curstate curstate().uuid_to_server[server_id] = server else: bokeh.io._state.uuid_to_server[server_id] = server server.start() url = 'http://%s:%d%s' % (notebook_url.split(':')[0], server.port, "/") script = server_document(url) div_html = "<div class='bokeh_class' id='{divid}'>{script}</div>" print('%html ' + div_html.format(script=script, divid=server_id))
def launch_server(): context = zmq.Context() origins = ["localhost:{}".format(5006)] apps = {'/': Application(FunctionHandler(partial(make_document, context)))} server = Server(apps, port=5006) 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 main(): curDir = os.path.dirname(__file__) plotData = pd.read_csv(os.path.join(curDir, 'test.csv')) """Launch the server and connect to it. """ global x_values, y_values x_values = plotData['Area'].values y_values = plotData['% of F'].values print("Preparing a bokeh application.") io_loop = IOLoop.current() bokeh_app = Application(FunctionHandler( modify_doc)) server = Server({"/": bokeh_app}, io_loop=io_loop) server.start() print("Opening Bokeh application on http://localhost:5006/") io_loop.add_callback(server.show, "/") io_loop.start()
def start_server(): print('starting server') loop = IOLoop.current() #loop.start() server = Server({'/': modify_doc}, port=9998, address='0.0.0.0', http_server_kwargs={'xheaders': True}, io_loop=loop, allow_websocket_origin=['*']) server.start() server.show('/') loop.spawn_callback(sdata.DataMineRT_async, key, loop) #cb = tornado.ioloop.PeriodicCallback(sdata.PushStationsDF, callback_time=500) #cb.start() #dmine_task = asyncio.create_task(sdata.DataMineRT_async(key, loop)) #loop.PeriodicCallback(sdata.DataMineRT_async, key, loop, callback_time=10000) server.run_until_shutdown() print('server was shutdown')
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, io_loop=self.loop, port=port, address=ip, check_unused_sessions_milliseconds=500, allow_websocket_origin=["*"], **self.server_kwargs) self.server.start() except (SystemExit, EnvironmentError): port = 0 if i == 4: raise
def runLogAnalysis(): server = Server( {'/': openLog}, port = settings.bokehPort, ) server.start() server.io_loop.add_callback(server.show, "/") server.io_loop.start() # alternative bokeh server form # bt = BokehTornado({'/': wcushow}) # baseserver = BaseServer(server.io_loop,bt,server._http) # baseserver.start() # baseserver.io_loop.start() # chck if the user want to open another log file if messagebox.askyesno("Question","Do you want to open another file?"): restart_program()
def __init__(self): Thread.__init__(self) self.server = Server({'/': self.modify_doc}, num_procs=1) self.server.start() # self.doc=curdoc() # self.fig = dict() # self.cds = dict() self.t_msg_new_d = Condition() self.d = dict( dict() ) self._x=0.0 self.d_x=1 self.d = dict( dict() ) self.source = ColumnDataSource()
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 #ServerLifecycleHandler(filename = "server_lifecycle.py") #20180706 start_time_server = timeit.default_timer() server = Server({'/bk_plotter': bk_plter.plot_doc}, \ io_loop=IOLoop(), \ allow_websocket_origin=["localhost:8011"], \ websocket_max_message_size = 9999999999 * 1024 * 1024) settings.log_level('fatal') settings.py_log_level('fatal') #server = Server({'/bk_plotter': bk_plter.plot_doc}, io_loop=IOLoop(), allow_websocket_origin=["172.20.101.16"], host="http://172.20.101.16:5006") #server = Server({'/bk_plotter': bk_plter.plot_doc}, io_loop=IOLoop(), allow_websocket_origin=["*"]) server.start() Handler.on_server_loaded = server_lifecycle.on_server_loaded(server) server.io_loop.start() print("\nserver loading time \n") print(timeit.default_timer() - start_time_server)
def main(): # parse command line arguments args = parse_args() # set the logger log = logging.getLogger("dashmd") log.setLevel(loglevel.get(args.log)) log.debug(f"Set log level to '{args.log}'") os.environ['BOKEH_PY_LOG_LEVEL'] = dashmd_loglevel_to_bokeh.get(args.log) os.environ['BOKEH_LOG_LEVEL'] = dashmd_loglevel_to_bokeh.get(args.log) log.debug( f"Set Bokeh log level to '{dashmd_loglevel_to_bokeh.get(args.log)}'") # start the server try: log.debug("Preparing the Bokeh server") # create tornado IO loop io_loop = IOLoop.current() # force bokeh to load resources from CDN (quick fix, not working with bokeh 1.4.0) os.environ['BOKEH_RESOURCES'] = 'cdn' # create app app_dir = os.path.dirname(os.path.realpath(__file__)) bokeh_app = Application( DirectoryHandler(filename=app_dir, argv=[args.default_dir, args.update, args.port])) # create server server = Server( {'/': bokeh_app}, io_loop=io_loop, port=args.port, num_procs=1, allow_websocket_origin=[f'localhost:{args.port}'], ) except OSError: log.error( f"[ERROR] Port {args.port} is already in use. Please specify a different one by using the --port flag." ) sys.exit(1) server.start() log.info(f"Opening DashMD on http://localhost:{args.port}") server.io_loop.add_callback(server.show, "/") server.io_loop.start()
def start(self): def plotter(doc): # Base data x = [item['x'] for item in self.data] y = [item['y'] for item in self.data] ds = ColumnDataSource(data=dict(x=x, y=y)) def update_plot(): new = {} if len(self.data): new = { 'x': [self.data[-1]['x']], 'y': [self.data[-1]['y']] } last = {} if len(ds.data['x']): last = {'x': [ds.data['x'][-1]], 'y': [ds.data['y'][-1]]} if new != last: print('Displaying new data') ds.stream(new) p = figure(plot_width=1200, plot_height=400) p.line('x', 'y', color="firebrick", line_width=2, source=ds) doc.add_periodic_callback(update_plot, 1000) doc.add_root(p) io_loop = IOLoop.current() bokeh_app = Application(FunctionHandler(plotter)) server = Server({'/': bokeh_app}, io_loop=io_loop, host="*") server.start() print('Opening Bokeh application on http://localhost:5006/') io_loop.add_callback(server.show, '/') 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=["*"], **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. " "Perhaps you already have a cluster running?" % port) else: msg = "Failed to start diagnostics server on port %d. " % port + str( exc) raise type(exc)(msg) if i == 4: raise
def _setup_server(apps, port, no_browser): """ Setup the server similarly to bokeh serve subcommand. In contrast to bokeh serve this supports being called from within a notebook. It also allows the server to be run in a separate thread while a main script is waiting for the output. Args: apps (dict): Dictionary mapping suffixes of the address to Applications. port (int): Port where to host the BokehServer. no_browser (bool): Whether to open the dashboard in the browser. Defaults to false. Has to be set to ``True`` for running on a remote server. """ # this is adapted from bokeh.subcommands.serve with report_server_init_errors(port=port): server = Server(apps, port=port) # On a remote server, we do not want to start the dashboard here. if not no_browser: def show_callback(): for route in apps.keys(): server.show(route) server.io_loop.add_callback(show_callback) address_string = server.address if server.address else "localhost" for route in sorted(apps): url = "http://{}:{}{}{}".format( address_string, server.port, server.prefix, route ) print("Bokeh app running at:", url) # For Windows, it is important that the server is started here as otherwise a # pickling error happens within multiprocess. See # https://stackoverflow.com/a/38236630/7523785 for more information. server._loop.start() 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()