Example #1
0
def test_build_single_handler_application_main_py(mock_warn):
    f = tempfile.NamedTemporaryFile(suffix="main.py", delete=False)
    f.close() #close file to open it later on windows
    util.build_single_handler_application(f.name)
    assert mock_warn.called
    assert mock_warn.call_args[0] == (DIRSTYLE_MAIN_WARNING_COPY,)
    os.remove(f.name)
def test_build_single_handler_application_main_py(mock_warn):
    f = tempfile.NamedTemporaryFile(suffix="main.py", delete=False)
    f.close()  #close file to open it later on windows
    util.build_single_handler_application(f.name)
    assert mock_warn.called
    assert mock_warn.call_args[0] == (DIRSTYLE_MAIN_WARNING_COPY, )
    os.remove(f.name)
Example #3
0
def test_server_examples(server_example, example, config, bokeh_server):
    # mitigate some weird interaction isolated to simple ids, py2.7,
    # "push_session" server usage, and TravisCI
    if six.PY2: os.environ['BOKEH_SIMPLE_IDS'] = 'no'
    app = build_single_handler_application(example.path)
    doc = app.create_document()
    if six.PY2: del os.environ['BOKEH_SIMPLE_IDS']

    # remove all next-tick, periodic, and timeout callbacks
    for session_callback in doc.session_callbacks:
        if isinstance(session_callback, NextTickCallback):
            doc.remove_next_tick_callback(session_callback)
        elif isinstance(session_callback, PeriodicCallback):
            doc.remove_periodic_callback(session_callback)
        elif isinstance(session_callback, TimeoutCallback):
            doc.remove_timeout_callback(session_callback)
        else:
            raise RuntimeError('Unhandled callback type', type(session_callback))

    session_id = basename(example.path)
    push_session(doc, session_id=session_id)

    if example.no_js:
        if not config.option.no_js:
            warn("skipping bokehjs for %s" % example.relpath)
    else:
        _run_in_browser(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, config.option.verbose)
Example #4
0
def test_server_examples(server_example, example, report, bokeh_server):
    if example.is_skip:
        pytest.skip("skipping %s" % example.relpath)

    app = build_single_handler_application(example.path)
    doc = app.create_document()

    # remove all next-tick, periodic, and timeout callbacks
    for session_callback in doc.session_callbacks:
        if isinstance(session_callback, NextTickCallback):
            doc.remove_next_tick_callback(session_callback)
        elif isinstance(session_callback, PeriodicCallback):
            doc.remove_periodic_callback(session_callback)
        elif isinstance(session_callback, TimeoutCallback):
            doc.remove_timeout_callback(session_callback)
        else:
            raise RuntimeError('Unhandled callback type', type(session_callback))

    session_id = basename(example.path)
    push_session(doc, session_id=session_id)

    if example.no_js:
        if not pytest.config.option.no_js:
            warn("skipping bokehjs for %s" % example.relpath)

    else:
        _assert_snapshot(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, 'server')

        if example.no_diff:
            warn("skipping image diff for %s" % example.relpath)
        else:
            _get_pdiff(example)
Example #5
0
 def _normalize(self, obj: ApplicationLike) -> Application:
     if callable(obj):
         return Application(FunctionHandler(obj))
     elif isinstance(obj, Path):
         return build_single_handler_application(obj)
     else:
         return obj
Example #6
0
    async def get(self, path, *args, **kwargs):
        if path in _APPS:
            app, context = _APPS[path]
        else:
            if path.endswith('yml') or path.endswith('.yaml'):
                from lumen.config import config
                from lumen.command import build_single_handler_application as build_lumen
                config.dev = True
                app = build_lumen(path, argv=None)
            else:
                app = build_single_handler_application(path)
            context = ApplicationContext(app, url=path)
            context._loop = tornado.ioloop.IOLoop.current()
            _APPS[path] = (app, context)

        self.application_context = context

        session = await self.get_session()

        page = server_html_page_for_session(
            session,
            resources=RESOURCES,
            title=session.document.title,
            template=session.document.template,
            template_variables=session.document.template_variables
        )

        self.set_header("Content-Type", 'text/html')
        self.write(page)
def test_server_examples(server_example, example, report, bokeh_server):
    if example.is_skip:
        pytest.skip("skipping %s" % example.relpath)

    app = build_single_handler_application(example.path)
    doc = app.create_document()

    # remove all periodic and timeout callbacks
    for session_callback in list(doc._session_callbacks.keys()):
        doc._remove_session_callback(session_callback)

    session_id = "session_id"
    push_session(doc, session_id=session_id)

    if example.no_js:
        if not pytest.config.option.no_js:
            warn("skipping bokehjs for %s" % example.relpath)

    else:
        _assert_snapshot(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, 'server')

        if example.no_diff:
            warn("skipping image diff for %s" % example.relpath)
        else:
            _get_pdiff(example)
Example #8
0
def test_server_examples(server_example, example, report, bokeh_server):
    if example.is_skip:
        pytest.skip("skipping %s" % example.relpath)

    app = build_single_handler_application(example.path)
    doc = app.create_document()

    # remove all periodic and timeout callbacks
    for session_callback in list(doc._session_callbacks.keys()):
        doc._remove_session_callback(session_callback)

    session_id = "session_id"
    push_session(doc, session_id=session_id)

    if example.no_js:
        if not pytest.config.option.no_js:
            warn("skipping bokehjs for %s" % example.relpath)

    else:
        _assert_snapshot(
            example, "http://localhost:5006/?bokeh-session-id=%s" % session_id,
            'server')

        if example.no_diff:
            warn("skipping image diff for %s" % example.relpath)
        else:
            _get_pdiff(example)
Example #9
0
    def _make_app(command: str,
                  url: str = "/",
                  debug: bool = False) -> Application:
        cwd_original = os.getcwd()

        # Command can be absolute, or could be relative to cwd
        app_py_path = os.path.join(os.getcwd(), command)

        if os.path.isdir(app_py_path):
            dirname = app_py_path
        else:
            dirname = os.path.dirname(app_py_path)

        if app_py_path == dirname:
            logger.debug("Fetching folder {}".format(app_py_path))
        else:
            logger.debug("Fetching script {}".format(app_py_path))

        if os.path.isdir(dirname):
            logger.debug("Changing working dir to {}".format(dirname))
            os.chdir(dirname)

        app = build_single_handler_application(app_py_path, [url])

        os.chdir(cwd_original)
        logger.debug("Changing working dir back to {}".format(cwd_original))

        return app
Example #10
0
def test_server_examples(server_example, example, report, config,
                         bokeh_server) -> None:
    if config.option.verbose:
        print()
    app = build_single_handler_application(example.path)
    doc = app.create_document()

    # remove all next-tick, periodic, and timeout callbacks
    for session_callback in doc.session_callbacks:
        if isinstance(session_callback, NextTickCallback):
            doc.remove_next_tick_callback(session_callback)
        elif isinstance(session_callback, PeriodicCallback):
            doc.remove_periodic_callback(session_callback)
        elif isinstance(session_callback, TimeoutCallback):
            doc.remove_timeout_callback(session_callback)
        else:
            raise RuntimeError('Unhandled callback type',
                               type(session_callback))

    session_id = basename(example.path)
    push_session(doc, session_id=session_id)

    if example.no_js:
        if not config.option.no_js:
            warn("skipping bokehjs for %s" % example.relpath)
    else:
        _run_in_browser(
            example, "http://localhost:5006/?bokeh-session-id=%s" % session_id,
            report, config.option.verbose)
Example #11
0
def test_server_examples(server_example, example, config, report, bokeh_server):
    # mitigate some weird interaction isolated to simple ids, py2.7,
    # "push_session" server usage, and TravisCI
    if six.PY2: os.environ['BOKEH_SIMPLE_IDS'] = 'no'
    app = build_single_handler_application(example.path)
    doc = app.create_document()
    if six.PY2: del os.environ['BOKEH_SIMPLE_IDS']

    # remove all next-tick, periodic, and timeout callbacks
    for session_callback in doc.session_callbacks:
        if isinstance(session_callback, NextTickCallback):
            doc.remove_next_tick_callback(session_callback)
        elif isinstance(session_callback, PeriodicCallback):
            doc.remove_periodic_callback(session_callback)
        elif isinstance(session_callback, TimeoutCallback):
            doc.remove_timeout_callback(session_callback)
        else:
            raise RuntimeError('Unhandled callback type', type(session_callback))

    session_id = basename(example.path)
    push_session(doc, session_id=session_id)

    if example.no_js:
        if not config.option.no_js:
            warn("skipping bokehjs for %s" % example.relpath)
    else:
        _run_in_browser(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, config.option.verbose)
Example #12
0
def test_server_examples(server_example, example, report, bokeh_server):
    if example.is_skip:
        pytest.skip("skipping %s" % example.relpath)

    app = build_single_handler_application(example.path)
    doc = app.create_document()

    # remove all next-tick, periodic, and timeout callbacks
    for session_callback in doc.session_callbacks:
        if isinstance(session_callback, NextTickCallback):
            doc.remove_next_tick_callback(session_callback)
        elif isinstance(session_callback, PeriodicCallback):
            doc.remove_periodic_callback(session_callback)
        elif isinstance(session_callback, TimeoutCallback):
            doc.remove_timeout_callback(session_callback)
        else:
            raise RuntimeError('Unhandled callback type', type(session_callback))

    session_id = basename(example.path)
    push_session(doc, session_id=session_id)

    if example.no_js:
        if not pytest.config.option.no_js:
            warn("skipping bokehjs for %s" % example.relpath)

    else:
        _assert_snapshot(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, 'server')

        if example.no_diff:
            warn("skipping image diff for %s" % example.relpath)
        else:
            _get_pdiff(example)
Example #13
0
 def __init__(self, index_path=None):
     application = build_single_handler_application(
         os.path.join(os.path.dirname(__file__), "app"))
     self.server = bkServer({'/app': application},
                            num_procs=1,
                            debug=True,
                            extra_patterns=[('/', IndexHandler)])
     self.server.start()
Example #14
0
def bk_worker():
    # path = os.path.abspath('visualization')
    visualization = build_single_handler_application('visualization')
    server = Server({'/visualization': visualization},
                    io_loop=IOLoop(),
                    allow_websocket_origin=['localhost:8001'],
                    address='0.0.0.0')
    server.start()
    server.io_loop.start()
Example #15
0
def bk_worker():
    """
    bokeh 后台server 启动
     :return:
    """
    # Can't pass num_procs > 1 in this configuration. If you need to run multiple
    # processes, see e.g. flask_gunicorn_embed.py
    # 启动时序图handler
    settings.resources = 'server'
    settings.allowed_ws_origin = '*'
    settings.log_level = 'debug'
    settings.minified = False
    # settings.py_log_level = 'debug'
    myapp = build_single_handler_application(
        os.path.join(os.path.dirname(__file__), "myapp"))
    stocks = build_single_handler_application(
        os.path.join(os.path.dirname(__file__), "stocks"))
    export_csv = build_single_handler_application(
        os.path.join(os.path.dirname(__file__), "export_csv"))
    ohlc = build_single_handler_application(
        os.path.join('G:\\dt-boot\\bokeh\\examples\\app', "ohlc"))
    dash = build_single_handler_application(
        os.path.join('G:\\dt-boot\\bokeh\\examples\\app', "dash"))
    # spectrogram = build_single_handler_application(os.path.join('G:\\dt-boot\\bokeh\\examples\\app', "spectrogram"))

    server = Server(
        {
            '/myapp': myapp,
            '/stocks': stocks,
            '/export_csv': export_csv,
            '/ohlc': ohlc,
            '/dash': dash
        },
        io_loop=IOLoop(),
        allow_websocket_origin=["*"])
    server.start()
    server.io_loop.start()
Example #16
0
def make_app(command, debug=False):

    # Command can be absolute, or could be relative to cwd
    app_py_path = os.path.join(os.getcwd(), command)

    print("Fetching Bokeh script or folder {}".format(app_py_path))

    dirname = os.path.dirname(app_py_path)

    if os.path.isdir(dirname):
        print("CWD to {}".format(dirname))
        os.chdir(dirname)

    app = build_single_handler_application(app_py_path, ['/'])

    return app
Example #17
0
    def ready(self):

        print("DjangoBokehConfig.ready()")
        os.environ['BOKEH_NODEJS_PATH'] = settings.BOKEH_NODEJS_PATH

        bokeh_app_base_path = os.path.join(settings.BASE_DIR, "djangobokeh",
                                           "bokeh_apps")
        path_list = glob.glob(os.path.join(bokeh_app_base_path, "*.py"))
        print(path_list)

        applications = {}
        for path in path_list:
            application = build_single_handler_application(path)

            route = application.handlers[0].url_path()

            if not route:
                if '/' in applications:
                    raise RuntimeError(
                        "Don't know the URL path to use for %s" % (path))
                route = '/'
            applications[route] = application

        if callable(applications):
            applications = Application(FunctionHandler(applications))

        if isinstance(applications, Application):
            applications = {'/': applications}

        for k, v in list(applications.items()):
            if callable(v):
                applications[k] = Application(FunctionHandler(v))
            if all(not isinstance(handler, DocumentLifecycleHandler)
                   for handler in applications[k]._handlers):
                applications[k].add(DocumentLifecycleHandler())

        self._applications = dict()

        for k, v in applications.items():
            self._applications[k] = ApplicationContext(v, url=k)

        self.routing_config = RoutingConfiguration(self._applications)
Example #18
0
def test_build_single_handler_application_nonexistent_file() -> None:
    with pytest.raises(ValueError) as e:
        util.build_single_handler_application("junkjunkjunk")
    assert "Path for Bokeh server application does not exist: " in str(e.value)
Example #19
0
def test_build_single_handler_application_unknown_file() -> None:
    with pytest.raises(ValueError) as e:
        f = tempfile.NamedTemporaryFile(suffix=".bad")
        util.build_single_handler_application(f.name)
    assert "Expected a '.py' script or '.ipynb' notebook, got: " in str(
        e.value)
def test_build_single_handler_application_main_py(mock_warn):
    f = tempfile.NamedTemporaryFile(suffix="main.py")
    util.build_single_handler_application(f.name)
    assert mock_warn.called
    assert mock_warn.call_args[0] == (DIRSTYLE_MAIN_WARNING_COPY, )
Example #21
0
def get_server(panel,
               port=0,
               address=None,
               websocket_origin=None,
               loop=None,
               show=False,
               start=False,
               title=None,
               verbose=False,
               location=True,
               static_dirs={},
               oauth_provider=None,
               oauth_key=None,
               oauth_secret=None,
               oauth_extra_params={},
               cookie_secret=None,
               oauth_encryption_key=None,
               session_history=None,
               **kwargs):
    """
    Returns a Server instance with this panel attached as the root
    app.

    Arguments
    ---------
    panel: Viewable, function or {str: Viewable}
      A Panel object, a function returning a Panel object or a
      dictionary mapping from the URL slug to either.
    port: int (optional, default=0)
      Allows specifying a specific port
    address : str
      The address the server should listen on for HTTP requests.
    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.
    loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())
      The tornado IOLoop to run the Server on.
    show : boolean (optional, default=False)
      Whether to open the server in a new browser tab on start.
    start : boolean(optional, default=False)
      Whether to start the Server.
    title : str or {str: str} (optional, default=None)
      An HTML title for the application or a dictionary mapping
      from the URL slug to a customized title.
    verbose: boolean (optional, default=False)
      Whether to report the address and port.
    location : boolean or panel.io.location.Location
      Whether to create a Location component to observe and
      set the URL location.
    static_dirs: dict (optional, default={})
      A dictionary of routes and local paths to serve as static file
      directories on those routes.
    oauth_provider: str
      One of the available OAuth providers
    oauth_key: str (optional, default=None)
      The public OAuth identifier
    oauth_secret: str (optional, default=None)
      The client secret for the OAuth provider
    oauth_extra_params: dict (optional, default={})
      Additional information for the OAuth provider
    cookie_secret: str (optional, default=None)
      A random secret string to sign cookies (required for OAuth)
    oauth_encryption_key: str (optional, default=False)
      A random encryption key used for encrypting OAuth user
      information and access tokens.
    session_history: int (optional, default=None)
      The amount of session history to accumulate. If set to non-zero
      and non-None value will launch a REST endpoint at
      /rest/session_info, which returns information about the session
      history.
    kwargs: dict
      Additional keyword arguments to pass to Server instance.

    Returns
    -------
    server : bokeh.server.server.Server
      Bokeh Server instance running this panel
    """
    from ..config import config
    from .rest import REST_PROVIDERS

    server_id = kwargs.pop('server_id', uuid.uuid4().hex)
    kwargs['extra_patterns'] = extra_patterns = kwargs.get(
        'extra_patterns', [])
    if isinstance(panel, dict):
        apps = {}
        for slug, app in panel.items():
            if isinstance(title, dict):
                try:
                    title_ = title[slug]
                except KeyError:
                    raise KeyError(
                        "Keys of the title dictionnary and of the apps "
                        f"dictionary must match. No {slug} key found in the "
                        "title dictionary.")
            else:
                title_ = title
            slug = slug if slug.startswith('/') else '/' + slug
            if 'flask' in sys.modules:
                from flask import Flask
                if isinstance(app, Flask):
                    wsgi = WSGIContainer(app)
                    if slug == '/':
                        raise ValueError(
                            'Flask apps must be served on a subpath.')
                    if not slug.endswith('/'):
                        slug += '/'
                    extra_patterns.append(
                        ('^' + slug + '.*', ProxyFallbackHandler,
                         dict(fallback=wsgi, proxy=slug)))
                    continue
            if isinstance(app, pathlib.Path):
                app = str(app)  # enables serving apps from Paths
            if (isinstance(app, str)
                    and (app.endswith(".py") or app.endswith(".ipynb"))
                    and os.path.isfile(app)):
                apps[slug] = build_single_handler_application(app)
            else:
                handler = FunctionHandler(
                    partial(_eval_panel, app, server_id, title_, location))
                apps[slug] = Application(handler)
    else:
        handler = FunctionHandler(
            partial(_eval_panel, panel, server_id, title, location))
        apps = {'/': Application(handler)}

    extra_patterns += get_static_routes(static_dirs)

    if session_history is not None:
        config.session_history = session_history
    if config.session_history != 0:
        pattern = REST_PROVIDERS['param']([], 'rest')
        extra_patterns.extend(pattern)
        state.publish('session_info', state, ['session_info'])

    opts = dict(kwargs)
    if loop:
        loop.make_current()
        opts['io_loop'] = loop
    elif opts.get('num_procs', 1) == 1:
        opts['io_loop'] = IOLoop.current()

    if 'index' not in opts:
        opts['index'] = INDEX_HTML

    if address is not None:
        opts['address'] = address

    if websocket_origin:
        if not isinstance(websocket_origin, list):
            websocket_origin = [websocket_origin]
        opts['allow_websocket_origin'] = websocket_origin

    # Configure OAuth
    from ..config import config
    if config.oauth_provider:
        from ..auth import OAuthProvider
        opts['auth_provider'] = OAuthProvider()
    if oauth_provider:
        config.oauth_provider = oauth_provider
    if oauth_key:
        config.oauth_key = oauth_key
    if oauth_extra_params:
        config.oauth_extra_params = oauth_extra_params
    if cookie_secret:
        config.cookie_secret = cookie_secret
    opts['cookie_secret'] = config.cookie_secret

    server = Server(apps, port=port, **opts)
    if verbose:
        address = server.address or 'localhost'
        url = f"http://{address}:{server.port}{server.prefix}"
        print(f"Launching server at {url}")

    state._servers[server_id] = (server, panel, [])

    if show:

        def show_callback():
            server.show('/login' if config.oauth_provider else '/')

        server.io_loop.add_callback(show_callback)

    def sig_exit(*args, **kwargs):
        server.io_loop.add_callback_from_signal(do_stop)

    def do_stop(*args, **kwargs):
        server.io_loop.stop()

    try:
        signal.signal(signal.SIGINT, sig_exit)
    except ValueError:
        pass  # Can't use signal on a thread

    if start:
        server.start()
        try:
            server.io_loop.start()
        except RuntimeError:
            pass
    return server
Example #22
0
def test_build_single_handler_application_unknown_file():
    with pytest.raises(ValueError):
        f = tempfile.NamedTemporaryFile(suffix=".bad")
        util.build_single_handler_application(f.name)
Example #23
0
def test_build_single_handler_application_main_py(mock_warn):
    f = tempfile.NamedTemporaryFile(suffix="main.py")
    util.build_single_handler_application(f.name)
    assert mock_warn.called
    assert mock_warn.call_args[0] == (DIRSTYLE_MAIN_WARNING_COPY,)
Example #24
0
def test_build_single_handler_application_unknown_file():
    with pytest.raises(ValueError) as e:
        f = tempfile.NamedTemporaryFile(suffix=".bad")
        util.build_single_handler_application(f.name)
    assert "Expected a '.py' script or '.ipynb' notebook, got: " in str(e)
Example #25
0
def test_build_single_handler_application_nonexistent_file():
    with pytest.raises(ValueError) as e:
        util.build_single_handler_application("junkjunkjunk")
    assert "Path for Bokeh server application does not exist: " in str(e)
Example #26
0
class IndexHandler(RequestHandler):
    def get(self):
        # template = env.get_template('embed.html')
        # script = server_document('http://localhost:5006/stocks')
        # self.write(template.render(script=script, template="Tornado"))
        self.write("")


# 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.
# The `static/` end point is reserved for Bokeh resources, as specified in
# bokeh.server.urls. In order to make your own end point for static resources,
# add the following to the `extra_patterns` argument, replacing `DIR` with the desired directory.
# (r'/DIR/(.*)', StaticFileHandler, {'path': os.path.normpath(os.path.dirname(__file__) + '/DIR')})
myapp = build_single_handler_application(
    os.path.join(os.path.dirname(__file__), "myapp"))
stocks = build_single_handler_application(
    os.path.join(os.path.dirname(__file__), "stocks"))
server = Server({
    '/myapp': myapp,
    '/stocks': stocks
},
                num_procs=1,
                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/'
Example #27
0
"""

from tornado.web import RequestHandler
from bokeh.settings import settings
import os
import sys

from bokeh.server.server import Server
from bokeh.command.util import build_single_handler_application

import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger()

settings.allowed_ws_origin = '*'
app = build_single_handler_application(
    os.path.join(os.path.dirname(__file__), "app"))

num_procs = 1 if sys.platform == "win32" else 4
server = Server({'/app': app}, num_procs=num_procs, port=8080)
server.start()

if __name__ == '__main__':
    from bokeh.util.browser import view

    print(
        'Opening Tornado app with embedded Bokeh application on http://localhost:8080/app'
    )

    server.io_loop.add_callback(view, "http://localhost:8080/app")
    server.io_loop.start()
Example #28
0
def test_build_single_handler_application_unknown_file():
    with pytest.raises(ValueError):
        f = tempfile.NamedTemporaryFile(suffix=".bad")
        util.build_single_handler_application(f.name)