def build_applications(self, args): if args.files: files = args.files else: files = [] applications = {} for file in files: file = os.path.abspath(file) if os.path.isdir(file): handler = DirectoryHandler(filename=file) else: handler = ScriptHandler(filename=file) if handler.failed: die("Error loading %s:\n\n%s\n%s " % (file, handler.error, handler.error_detail)) application = Application() application.add(handler) route = handler.url_path() if not route: if '/' in applications: die("Don't know the URL path to use for %s" % (file)) route = '/' applications[route] = application if len(applications) == 0: # create an empty application by default, used with output_server typically applications['/'] = Application() return applications
def load(filename): handler = DirectoryHandler(filename=filename) assert handler.safe_to_fork result['handler'] = handler handler.modify_document(doc) if handler.failed: raise RuntimeError(handler.error) assert not handler.safe_to_fork
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.info("Preparing the Bokeh server") io_loop = IOLoop.current() # force bokeh to load resources from CDN os.environ['BOKEH_RESOURCES'] = 'cdn' app_dir = os.path.dirname(os.path.realpath(__file__)) bokeh_app = Application(DirectoryHandler(filename=app_dir, argv=[args.default_dir, args.update])) 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 build_single_handler_application(path): ''' Return a Bokeh application built using a single handler for a file or directory. Args: path (str) : path to a file or directory for creating a Bokeh application. Returns: Application Raises: RuntimeError ''' path = os.path.abspath(path) if os.path.isdir(path): handler = DirectoryHandler(filename=path) else: handler = ScriptHandler(filename=path) if handler.failed: raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail)) application = Application(handler) return application
def main(): """The photodiag command line interface. This is a wrapper around bokeh server that provides an interface to launch applications bundled with the photodiag package. """ # Discover photodiag apps apps_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'apps') available_apps = [] for module_info in pkgutil.iter_modules([apps_path]): if module_info.ispkg: available_apps.append(module_info.name) parser = argparse.ArgumentParser( prog='photodiag', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'app', type=str, choices=available_apps, help="photodiag application", ) parser.add_argument('--port', type=int, default=5006, help="the port to listen on for HTTP requests") parser.add_argument( '--allow-websocket-origin', metavar='HOST[:PORT]', type=str, action='append', default=None, help="hostname that can connect to the server websocket", ) parser.add_argument( '--args', nargs=argparse.REMAINDER, default=[], help="command line arguments for the photodiag application", ) args = parser.parse_args() app_path = os.path.join(apps_path, args.app) logger.info(app_path) handler = DirectoryHandler(filename=app_path, argv=args.args) server = Server( {'/': Application(handler)}, port=args.port, allow_websocket_origin=args.allow_websocket_origin, ) server.start() server.io_loop.start()
def build_single_handler_application(path, argv=None): ''' Return a Bokeh application built using a single handler for a script, notebook, or directory. In general a Bokeh :class:`~bokeh.application.application.Application` may have any number of handlers to initialize :class:`~bokeh.document.Document` objects for new client sessions. However, in many cases only a single handler is needed. This function examines the ``path`` provided, and returns an ``Application`` initialized with one of the following handlers: * :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path`` is to a ``.py`` script. * :class:`~bokeh.application.handlers.notebook.NotebookHandler` when ``path`` is to an ``.ipynb`` Jupyter notebook. * :class:`~bokeh.application.handlers.directory.DirectoryHandler` when ``path`` is to a directory containing a ``main.py`` script. Args: path (str) : path to a file or directory for creating a Bokeh application. argv (seq[str], optional) : command line arguments to pass to the application handler Returns: :class:`~bokeh.application.application.Application` Raises: RuntimeError Notes: If ``path`` ends with a file ``main.py`` then a warning will be printed regarding running directory-style apps by passing the directory instead. ''' argv = argv or [] path = os.path.abspath(path) if os.path.isdir(path): handler = DirectoryHandler(filename=path, argv=argv) else: if path.endswith(".ipynb"): handler = NotebookHandler(filename=path, argv=argv) elif path.endswith(".py"): if path.endswith("main.py"): warnings.warn(DIRSTYLE_MAIN_WARNING) handler = ScriptHandler(filename=path, argv=argv) else: raise ValueError( "Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path) if handler.failed: raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail)) application = Application(handler) return application
def build_single_handler_application(path): ''' Return a Bokeh application built using a single handler for a file or directory. Args: path (str) : path to a file or directory for creating a Bokeh application. Returns: Application Raises: RuntimeError ''' path = os.path.abspath(path) if os.path.isdir(path): handler = DirectoryHandler(filename=path) else: if path.endswith(".ipynb"): handler = NotebookHandler(filename=path) elif path.endswith(".py"): handler = ScriptHandler(filename=path) else: raise ValueError("Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path) if handler.failed: raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail)) application = Application(handler) return application
def run_viewer(results_path: Union[Path, str], port: int = 5007, starting_index: int = 0): print(f'Opening viewer on http://localhost:{port}/') handler = DirectoryHandler(filename=str(Path(__file__).parent), argv=[results_path, starting_index]) application = Application(handler) server = Server(application, port=port) server.start() server.io_loop.add_callback(server.show, "/") server.io_loop.start()
def main(appnames, applist_file, port, allow_origin): env = Environment(loader=FileSystemLoader('templates')) class IndexHandler(RequestHandler): def get(self): template = env.get_template('index.html') #script = server_document('http://localhost:5006/app-base') self.write(template.render(applist=apps)) if appnames == None: print( "No appname provided on command line \n Trying to read app names from: ", applist_file) try: with open(applist_file) as file: apps = [line.strip() for line in file] print("found ", len(apps)) #,sep=":") print(apps) except: sys.exit("Not found ! You need to provide appnames") else: apps = appnames serverlist = {} bokeh_app = [] for i in range(len(apps)): # libfolder=os.path.join(os.path.abspath(os.path.dirname(__file__)),apps[0]) # print (libfolder) # sys.path.insert(0, libfolder) print("adding ", apps[i]) # ,sep=":" ) bokeh_app.append(Application(DirectoryHandler(filename=apps[i]))) rpath = '/' + str(apps[i]) serverlist[rpath] = bokeh_app[i] #server = Server({'/Qm7b': bokeh_app, '/Arginine-Dipeptide':bokeh_app2 }, num_procs=1,port=5001, extra_patterns=[('/', IndexHandler),("/static", StaticFileHandler, {'path':'static/'})]) server = Server(serverlist, num_procs=1, use_xheaders=False, port=port, allow_websocket_origin=allow_origin, extra_patterns=[('/', IndexHandler), (r"/static/(.*)", StaticFileHandler, { "path": "./static" })]) #server = Server({'/app-base': bokeh_app }, num_procs=1, port=5001) server.start() return server
def run(self) -> None: self.settings.setup_elasticsearch_connection() # The following is a simpler `bokeh serve src/nasty_analysis/visualization`. # Code for that is in `bokeh.commands.subcommands.serve.Serve.invoke`. # Also Bokeh provides this example: # https://github.com/bokeh/bokeh/blob/2.0.2/examples/howto/server_embed/standalone_embed.py address = self.settings.analysis.serve.address port = self.settings.analysis.serve.port num_procs = self.settings.analysis.num_procs autoreload = False if self.develop: num_procs = 1 autoreload = True watch(str(self.settings.find_settings_file())) for file in Path(nasty_analysis.__file__).parent.glob("**/*.js"): watch(str(file)) application = ParameterPassingApplication( DirectoryHandler(filename=Path(serve.__file__).parent), server_context_params={"settings": self.settings}, ) with report_server_init_errors(address=address, port=port): server = Server( {"/": application}, address=address, port=port, allow_websocket_origin=[f"{address}:{port}"], num_procs=num_procs, autoreload=autoreload, ) server.start() if self.show: server.io_loop.add_callback(server.show, "/") server.run_until_shutdown()
def build_single_handler_application(path, argv=None): ''' Return a Bokeh application built using a single handler for a file or directory. Args: path (str) : path to a file or directory for creating a Bokeh application. argv (seq[str], optional) : command line arguments to pass to the application handler Returns: Application Raises: RuntimeError ''' argv = argv or [] path = os.path.abspath(path) if os.path.isdir(path): handler = DirectoryHandler(filename=path, argv=argv) else: if path.endswith(".ipynb"): handler = NotebookHandler(filename=path, argv=argv) elif path.endswith(".py"): if path.endswith("main.py"): warnings.warn(DIRSTYLE_MAIN_WARNING) handler = ScriptHandler(filename=path, argv=argv) else: raise ValueError( "Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path) if handler.failed: raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail)) application = Application(handler) return application
def start_bokeh_server(): """ Create and start a bokeh server with a series of applications. """ # Declare the absolute path to the demo application. demo_path = os.path.abspath("project/server/bokeh_apps/bokehDemo") # Declare the dictionary of applications to launch. apps = { '/bokehDemo': Application(DirectoryHandler(filename=demo_path)), } # Instantiate the Bokeh server. # Allow connections from the Flask application. server = Server( applications=apps, allow_websocket_origin=["127.0.0.1:5000"], # port=5006 ) server.start() server.io_loop.start()
def load(filename): handler = DirectoryHandler(filename=filename) handler.modify_document(doc) if handler.failed: raise RuntimeError(handler.error)
if args.thiel: show_thiel = True if args.file is not None: ulog_file = os.path.abspath(args.file) show_ulog_file = True args.show = True show_3d_page = args.threed show_pid_analysis_page = args.pid_analysis applications = {} if args.show: thiel_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'thiel_app') print("this is the main file path", thiel_path) handler = DirectoryHandler(filename=thiel_path) applications['/thiel_app'] = Application(handler) set_log_id_is_filename(show_ulog_file) # additional request handlers extra_patterns = [ (r'/upload', UploadHandler), (r'/browse', BrowseHandler), (r'/browse_data_retrieval', BrowseDataRetrievalHandler), (r'/3d', ThreeDHandler), (r'/radio_controller', RadioControllerHandler), (r'/edit_entry', EditEntryHandler), (r'/download', DownloadHandler), (r'/dbinfo', DBInfoHandler), (r'/error_label', UpdateErrorLabelHandler),
'--allow-websocket-origin', action='append', type=str, metavar='HOST[:PORT]', help="""Public hostnames which may connect to the Bokeh websocket""", default=None) args = parser.parse_args() # This should remain here until --host is removed entirely _fixup_deprecated_host_args(args) applications = {} main_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'plot_app') handler = DirectoryHandler(filename=main_path) applications['/plot_app'] = Application(handler) server_kwargs = {} if args.port != None: server_kwargs['port'] = args.port if args.use_xheaders: server_kwargs['use_xheaders'] = args.use_xheaders server_kwargs['num_procs'] = args.numprocs if args.address != None: server_kwargs['address'] = args.address if args.host != None: server_kwargs['host'] = args.host if args.allow_websocket_origin != None: server_kwargs['allow_websocket_origin'] = args.allow_websocket_origin # increase the maximum upload size (default is 100MB) server_kwargs['http_server_kwargs'] = {'max_buffer_size': 300 * 1024 * 1024} show_ulog_file = False
def build_single_handler_application(path: str, argv: List[str] | None = None ) -> Application: ''' Return a Bokeh application built using a single handler for a script, notebook, or directory. In general a Bokeh :class:`~bokeh.application.application.Application` may have any number of handlers to initialize |Document| objects for new client sessions. However, in many cases only a single handler is needed. This function examines the ``path`` provided, and returns an ``Application`` initialized with one of the following handlers: * :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path`` is to a ``.py`` script. * :class:`~bokeh.application.handlers.notebook.NotebookHandler` when ``path`` is to an ``.ipynb`` Jupyter notebook. * :class:`~bokeh.application.handlers.directory.DirectoryHandler` when ``path`` is to a directory containing a ``main.py`` script. Args: path (str) : path to a file or directory for creating a Bokeh application. argv (seq[str], optional) : command line arguments to pass to the application handler Returns: :class:`~bokeh.application.application.Application` Raises: RuntimeError Notes: If ``path`` ends with a file ``main.py`` then a warning will be printed regarding running directory-style apps by passing the directory instead. ''' argv = argv or [] path = os.path.abspath(os.path.expanduser(path)) handler: Handler # There are certainly race conditions here if the file/directory is deleted # in between the isdir/isfile tests and subsequent code. But it would be a # failure if they were not there to begin with, too (just a different error) if os.path.isdir(path): handler = DirectoryHandler(filename=path, argv=argv) elif os.path.isfile(path): if path.endswith(".ipynb"): handler = NotebookHandler(filename=path, argv=argv) elif path.endswith(".py"): if path.endswith("main.py"): warnings.warn(DIRSTYLE_MAIN_WARNING) handler = ScriptHandler(filename=path, argv=argv) else: raise ValueError( "Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path) else: raise ValueError( "Path for Bokeh server application does not exist: %s" % path) if handler.failed: raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail)) application = Application(handler) return application
# in the app model_map = Model.model_class_reverse_map for _, cm in CUSTOM_BOKEH_MODELS: if cm in model_map: del model_map[cm] return js_code if __name__ == '__main__': os.environ['BOKEH_RESOURCES'] = 'cdn' loglevel = os.getenv('ADVI_LOGLEVEL', 'INFO') logging.basicConfig(level=loglevel, format='%(asctime)s %(message)s') custom_js = compile_custom_models() apps = { make_url(arg): Application(DirectoryHandler(filename='app', argv=[arg, custom_js])) for _, arg in MENU_VARS } extra_patterns = [(make_url('?'), IndexHandler), (make_url('(favicon.ico)'), StaticFileHandler, { 'path': "app/static" }), (make_url('static/(.*)'), StaticHandler)] paths = [a[0] for a in extra_patterns] paths.extend(list(apps.keys())) logging.info('Running on localhost:5006 with paths:\n%s', '\n'.join(paths)) server = Server( apps, allow_websocket_origin=[WS_ORIGIN], use_xheaders=True, extra_patterns=extra_patterns,
def test_missing_filename_raises(): with pytest.raises(ValueError): DirectoryHandler()