Example #1
0
def create_bokeh_server(io_loop, files, argvs, host, port):
    '''Start bokeh server with applications paths'''
    from bokeh.server.server import Server
    from bokeh.command.util import build_single_handler_applications

    # Turn file paths into bokeh apps
    apps = build_single_handler_applications(files, argvs)

    # kwargs lifted from bokeh serve call to Server, with created io_loop
    kwargs = {
        'io_loop':
        io_loop,
        'generate_session_ids':
        True,
        'redirect_root':
        True,
        'secret_key':
        None,
        'num_procs':
        1,
        'sign_sessions':
        False,
        'port':
        port,
        'use_index':
        True,
        'allow_websocket_origin': [
            'localhost:5006', '127.0.0.1:5006', '10.7.61.53:5006',
            '10.7.61.53:80'
        ]
        #,'prefix' :'/'
    }
    server = Server(apps, **kwargs)

    return server
Example #2
0
def create_bokeh_server(io_loop, files, argvs, host, port):
    '''Start bokeh server with applications paths'''
    from bokeh.server.server import Server
    from bokeh.command.util import build_single_handler_applications

    # Turn file paths into bokeh apps
    apps = build_single_handler_applications(files, argvs)

    # kwargs lifted from bokeh serve call to Server, with created io_loop
    kwargs = {
        'io_loop': io_loop,
        'generate_session_ids': True,
        'redirect_root': True,
        'use_x_headers': False,
        'secret_key': None,
        'num_procs': 1,
        #'host': host,
        'sign_sessions': False,
        'develop': False,
        'port': port,
        'use_index': True,
        "check_unused_sessions": 0,
        "unused_session_lifetime": 0,
    }
    #  set this to some subdomain like: *.ngrok.io
    server = Server(apps, host=['*'], allow_websocket_origin=["*"], **kwargs)

    return server
Example #3
0
def start_server(filepath: str, host: str, port: int):
	files = [filepath]
	argvs = {}
	urls = []
	for f in files:
		argvs[f]=None
		urls.append(f.split('/')[-1].split('.')[0])
	io_loop = IOLoop.instance()
	apps = build_single_handler_applications(files,argvs)
	kwags = {
		'io_loop':io_loop,
		'generade_session_ids':True,
		'redirect_root':True,
		'use_x_headers':False,
		'secret_key':None,
		'num_procs':1,
		'host':['%s:%d'%(host, port)],
		'sign_sessions':False,
		'develop':False,
		'port':port, 
		'use_index':True
	}
	srv = Server(apps,**kwags)
	io_loop.add_callback(view, 'http://{}:{}'.format(host, port))
	io_loop.start()
Example #4
0
    def create_bokeh_server(io_loop, files, argvs, host, port):
        '''Start bokeh server with applications paths'''
        from bokeh.server.server import Server
        from bokeh.command.util import build_single_handler_applications

        # Turn file paths into bokeh apps
        apps = build_single_handler_applications(files, argvs)

        # kwargs lifted from bokeh serve call to Server, with created io_loop
        kwargs = {
            'io_loop': io_loop,
            'generate_session_ids': True,
            'redirect_root': True,
            'use_x_headers': False,
            'secret_key': None,
            'num_procs': 1,
            'host': host,
            'sign_sessions': False,
            'develop': False,
            'port': port,
            'use_index': True
        }
        server = Server(apps, **kwargs)

        return server
Example #5
0
def directory(*apps_paths: Path) -> List[Routing]:
    paths: List[Path] = []

    for apps_path in apps_paths:
        if apps_path.exists():
            paths += [ entry for entry in apps_path.glob("*") if is_bokeh_app(entry) ]
        else:
            log.warn("bokeh applications directory '{}' doesn't exist".format(apps_path))

    return [ document(url, app) for url, app in build_single_handler_applications(paths).items() ]
Example #6
0
def run_bokeh_server(bok_io_loop):
    files = ['whoseline_vis/plot.py']
    args = {k: None for k in files}

    apps = build_single_handler_applications(files, args)

    kwargs = {
        'io_loop': bok_io_loop,
        # 'redirect_root': True,
        # 'num_procs': 1,
        # 'sign_sessions': False,
        # 'host':['%s:%d' % (host,app_port),'%s:%d' % (host,bokeh_port)],
        # 'port': bokeh_port,
        # 'use_index': True,
        'allow_websocket_origin': ['%s:%d' % (host, remote_port)]
    }
    srv = Server(apps, **kwargs)
Example #7
0
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)
Example #8
0
 def setup_bokeh_server(self):
     ##turn file paths into bokeh apps
     files = ['plot_app']
     argvs = {}
     for i in files:
         argvs[i] = None
     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':
         self.bok_io_loop,
         'generade_session_ids':
         True,
         'redirect_root':
         True,
         'use_x_headers':
         False,
         'check_unused_sessions_milliseconds':
         1000,
         'unused_session_lifetime_milliseconds':
         5000,
         'secret_key':
         None,
         'num_procs':
         1,
         'host': [
             '%s:%d' % ('127.0.0.1', FLASK_PORT),
             '%s:%d' % ('127.0.0.1', self.port)
         ],
         'sign_sessions':
         False,
         'develop':
         False,
         'port':
         self.port,
         'use_index':
         True
     }
     self.ser = Server(apps, **kwags)
Example #9
0
    def setup_bokeh(self):
        ##turn file paths into bokeh apps
        apps = build_single_handler_applications(self.app_path_dict.keys(),
                                                 self.app_path_dict)

        ##kwargs lifted from bokeh serve call to Server, with the addition of my own io_loop
        kwargs = {
            'io_loop':
            self.io_loop,
            'generade_session_ids':
            True,
            'redirect_root':
            True,
            'use_x_headers':
            False,
            'secret_key':
            None,
            'num_procs':
            1,
            'host': [
                '%s:%d' % (self.host, self.app_port),
                '%s:%d' % (self.host, self.bokeh_port)
            ],
            'sign_sessions':
            False,
            'develop':
            False,
            'port':
            self.bokeh_port,
            'use_index':
            True
        }
        #instantiate the bokeh server
        srv = Server(apps, **kwargs)

        #return bokes object
        return srv
Example #10
0
    def customize_kwargs(self, args, server_kwargs):
        '''Allows subclasses to customize ``server_kwargs``.

        Should modify and return a copy of the ``server_kwargs`` dictionary.
        '''
        kwargs = dict(server_kwargs)
        if 'index' not in kwargs:
            kwargs['index'] = INDEX_HTML

        # Handle tranquilized functions in the supplied functions
        kwargs['extra_patterns'] = patterns = kwargs.get('extra_patterns', [])

        if args.static_dirs:
            static_dirs = parse_vars(args.static_dirs)
            patterns += get_static_routes(static_dirs)

        files = []
        for f in args.files:
            if args.glob:
                files.extend(glob(f))
            else:
                files.append(f)

        if args.index and not args.index.endswith('.html') and not any(f.endswith(args.index) for f in files):
            raise ValueError("The --index argument must either specify a jinja2 "
                             "template with a .html file extension or select one "
                             "of the applications being served as the default. "
                             f"The specified application {args.index!r} could "
                             "not be found.")

        # Handle tranquilized functions in the supplied functions
        if args.rest_provider in REST_PROVIDERS:
            pattern = REST_PROVIDERS[args.rest_provider](files, args.rest_endpoint)
            patterns.extend(pattern)
        elif args.rest_provider is not None:
            raise ValueError("rest-provider %r not recognized." % args.rest_provider)

        config.autoreload = args.autoreload

        if config.autoreload:
            for f in files:
                watch(f)

        if args.warm or args.autoreload:
            argvs = {f: args.args for f in files}
            applications = build_single_handler_applications(files, argvs)
            if args.autoreload:
                with record_modules():
                    for app in applications.values():
                        doc = app.create_document()
                        _cleanup_doc(doc)
            else:
                for app in applications.values():
                    doc = app.create_document()
                    _cleanup_doc(doc)

        config.profiler = args.profiler
        if args.admin:
            from ..io.admin import admin_panel
            from ..io.server import per_app_patterns
            config._admin = True
            app = Application(FunctionHandler(admin_panel))
            app_ctx = ApplicationContext(app, url='/admin')
            app_patterns = []
            for p in per_app_patterns:
                route = '/admin' + p[0]
                context = {"application_context": app_ctx}
                route = (args.prefix or '') + route
                app_patterns.append((route, p[1], context))

            from tornado.ioloop import IOLoop
            app_ctx._loop = IOLoop.current()

            websocket_path = None
            for r in app_patterns:
                if r[0].endswith("/ws"):
                    websocket_path = r[0]
            if not websocket_path:
                raise RuntimeError("Couldn't find websocket path")
            for r in app_patterns:
                r[2]["bokeh_websocket_path"] = websocket_path
            try:
                import snakeviz
                SNAKEVIZ_PATH = os.path.join(os.path.dirname(snakeviz.__file__), 'static')
                app_patterns.append(
                    ('/snakeviz/static/(.*)', StaticFileHandler, dict(path=SNAKEVIZ_PATH))
                )
            except Exception:
                pass
            patterns.extend(app_patterns)


        config.session_history = args.session_history
        if args.rest_session_info:
            pattern = REST_PROVIDERS['param'](files, 'rest')
            patterns.extend(pattern)
            state.publish('session_info', state, ['session_info'])

        if args.oauth_provider:
            config.oauth_provider = args.oauth_provider
            if config.oauth_key and args.oauth_key:
                raise ValueError(
                    "Supply OAuth key either using environment variable "
                    "or via explicit argument, not both."
                )
            elif args.oauth_key:
                config.oauth_key = args.oauth_key
            elif not config.oauth_key:
                raise ValueError(
                    "When enabling an OAuth provider you must supply "
                    "a valid oauth_key either using the --oauth-key "
                    "CLI argument or PANEL_OAUTH_KEY environment "
                    "variable."
                )

            if config.oauth_secret and args.oauth_secret:
                raise ValueError(
                    "Supply OAuth secret either using environment variable "
                    "or via explicit argument, not both."
                )
            elif args.oauth_secret:
                config.oauth_secret = args.oauth_secret
            elif not config.oauth_secret:
                raise ValueError(
                    "When enabling an OAuth provider you must supply "
                    "a valid OAuth secret either using the --oauth-secret "
                    "CLI argument or PANEL_OAUTH_SECRET environment "
                    "variable."
                )

            if args.oauth_extra_params:
                config.oauth_extra_params = ast.literal_eval(args.oauth_extra_params)

            if config.oauth_encryption_key and args.oauth_encryption_key:
                raise ValueError(
                    "Supply OAuth encryption key either using environment "
                    "variable or via explicit argument, not both."
                )
            elif args.oauth_encryption_key:
                encryption_key = args.oauth_encryption_key.encode('ascii')
                try:
                    key = base64.urlsafe_b64decode(encryption_key)
                except Exception:
                    raise ValueError("OAuth encryption key was not a valid base64 "
                                     "string. Generate an encryption key with "
                                     "`panel oauth-secret` and ensure you did not "
                                     "truncate the returned string.")
                if len(key) != 32:
                    raise ValueError(
                        "OAuth encryption key must be 32 url-safe "
                        "base64-encoded bytes."
                    )
                config.oauth_encryption_key = encryption_key
            else:
                print("WARNING: OAuth has not been configured with an "
                      "encryption key and will potentially leak "
                      "credentials in cookies and a JWT token embedded "
                      "in the served website. Use at your own risk or "
                      "generate a key with the `panel oauth-key` CLI "
                      "command and then provide it to `panel serve` "
                      "using the PANEL_OAUTH_ENCRYPTION environment "
                      "variable or the --oauth-encryption-key CLI "
                      "argument.")

            if config.oauth_encryption_key:
                try:
                    from cryptography.fernet import Fernet
                except ImportError:
                    raise ImportError(
                        "Using OAuth2 provider with Panel requires the "
                        "cryptography library. Install it with `pip install "
                        "cryptography` or `conda install cryptography`."
                    )
                state.encryption = Fernet(config.oauth_encryption_key)

            if args.cookie_secret and config.cookie_secret:
                raise ValueError(
                    "Supply cookie secret either using environment "
                    "variable or via explicit argument, not both."
                )
            elif args.cookie_secret:
                config.cookie_secret = args.cookie_secret
            else:
                raise ValueError(
                    "When enabling an OAuth provider you must supply "
                    "a valid cookie_secret either using the --cookie-secret "
                    "CLI argument or the PANEL_COOKIE_SECRET environment "
                    "variable."
                )
            kwargs['auth_provider'] = OAuthProvider()

            if args.oauth_redirect_uri and config.oauth_redirect_uri:
                raise ValueError(
                    "Supply OAuth redirect URI either using environment "
                    "variable or via explicit argument, not both."
                )
            elif args.oauth_redirect_uri:
                config.oauth_redirect_uri = args.oauth_redirect_uri

            if args.oauth_jwt_user and config.oauth_jwt_user:
                raise ValueError(
                    "Supply OAuth JWT user either using environment "
                    "variable or via explicit argument, not both."
                )
            elif args.oauth_jwt_user:
                config.oauth_jwt_user = args.oauth_jwt_user

        if config.cookie_secret:
            kwargs['cookie_secret'] = config.cookie_secret

        return kwargs
Example #11
0
    def customize_kwargs(self, args, server_kwargs):
        '''Allows subclasses to customize ``server_kwargs``.

        Should modify and return a copy of the ``server_kwargs`` dictionary.
        '''
        kwargs = dict(server_kwargs)
        if 'index' not in kwargs:
            kwargs['index'] = INDEX_HTML

        # Handle tranquilized functions in the supplied functions
        kwargs['extra_patterns'] = patterns = kwargs.get('extra_patterns', [])

        if args.static_dirs:
            static_dirs = parse_vars(args.static_dirs)
            patterns += get_static_routes(static_dirs)

        files = []
        for f in args.files:
            if args.glob:
                files.extend(glob(f))
            else:
                files.append(f)

        # Handle tranquilized functions in the supplied functions
        if args.rest_provider in REST_PROVIDERS:
            pattern = REST_PROVIDERS[args.rest_provider](files,
                                                         args.rest_endpoint)
            patterns.extend(pattern)
        elif args.rest_provider is not None:
            raise ValueError("rest-provider %r not recognized." %
                             args.rest_provider)

        config.autoreload = args.autoreload

        if config.autoreload:
            for f in files:
                watch(f)

        if args.warm or args.autoreload:
            argvs = {f: args.args for f in files}
            applications = build_single_handler_applications(files, argvs)
            with record_modules():
                for app in applications.values():
                    app.create_document()

        config.session_history = args.session_history
        if args.rest_session_info:
            pattern = REST_PROVIDERS['param'](files, 'rest')
            patterns.extend(pattern)
            state.publish('session_info', state, ['session_info'])

        if args.oauth_provider:
            config.oauth_provider = args.oauth_provider
            if config.oauth_key and args.oauth_key:
                raise ValueError(
                    "Supply OAuth key either using environment variable "
                    "or via explicit argument, not both.")
            elif args.oauth_key:
                config.oauth_key = args.oauth_key
            elif not config.oauth_key:
                raise ValueError(
                    "When enabling an OAuth provider you must supply "
                    "a valid oauth_key either using the --oauth-key "
                    "CLI argument or PANEL_OAUTH_KEY environment "
                    "variable.")

            if config.oauth_secret and args.oauth_secret:
                raise ValueError(
                    "Supply OAuth secret either using environment variable "
                    "or via explicit argument, not both.")
            elif args.oauth_secret:
                config.oauth_secret = args.oauth_secret
            elif not config.oauth_secret:
                raise ValueError(
                    "When enabling an OAuth provider you must supply "
                    "a valid OAuth secret either using the --oauth-secret "
                    "CLI argument or PANEL_OAUTH_SECRET environment "
                    "variable.")

            if args.oauth_extra_params:
                config.oauth_extra_params = ast.literal_eval(
                    args.oauth_extra_params)

            if config.oauth_encryption_key and args.oauth_encryption_key:
                raise ValueError(
                    "Supply OAuth encryption key either using environment "
                    "variable or via explicit argument, not both.")
            elif args.oauth_encryption_key:
                encryption_key = args.oauth_encryption_key.encode('ascii')
                try:
                    key = base64.urlsafe_b64decode(encryption_key)
                except Exception:
                    raise ValueError(
                        "OAuth encryption key was not a valid base64 "
                        "string. Generate an encryption key with "
                        "`panel oauth-secret` and ensure you did not "
                        "truncate the returned string.")
                if len(key) != 32:
                    raise ValueError(
                        "OAuth encryption key must be 32 url-safe "
                        "base64-encoded bytes.")
                config.oauth_encryption_key = encryption_key
            else:
                print("WARNING: OAuth has not been configured with an "
                      "encryption key and will potentially leak "
                      "credentials in cookies and a JWT token embedded "
                      "in the served website. Use at your own risk or "
                      "generate a key with the `panel oauth-key` CLI "
                      "command and then provide it to `panel serve` "
                      "using the PANEL_OAUTH_ENCRYPTION environment "
                      "variable or the --oauth-encryption-key CLI "
                      "argument.")

            if config.oauth_encryption_key:
                try:
                    from cryptography.fernet import Fernet
                except ImportError:
                    raise ImportError(
                        "Using OAuth2 provider with Panel requires the "
                        "cryptography library. Install it with `pip install "
                        "cryptography` or `conda install cryptography`.")
                state.encryption = Fernet(config.oauth_encryption_key)

            if args.cookie_secret and config.cookie_secret:
                raise ValueError(
                    "Supply cookie secret either using environment "
                    "variable or via explicit argument, not both.")
            elif args.cookie_secret:
                config.cookie_secret = args.cookie_secret
            else:
                raise ValueError(
                    "When enabling an OAuth provider you must supply "
                    "a valid cookie_secret either using the --cookie-secret "
                    "CLI argument or the PANEL_COOKIE_SECRET environment "
                    "variable.")
            kwargs['auth_provider'] = OAuthProvider()

            if args.oauth_redirect_uri and config.oauth_redirect_uri:
                raise ValueError(
                    "Supply OAuth redirect URI either using environment "
                    "variable or via explicit argument, not both.")
            elif args.oauth_redirect_uri:
                config.oauth_redirect_uri = args.oauth_redirect_uri

            if args.oauth_jwt_user and config.oauth_jwt_user:
                raise ValueError(
                    "Supply OAuth JWT user either using environment "
                    "variable or via explicit argument, not both.")
            elif args.oauth_jwt_user:
                config.oauth_jwt_user = args.oauth_jwt_user

        if config.cookie_secret:
            kwargs['cookie_secret'] = config.cookie_secret

        return kwargs