Python bokeh.server.server.Server() Examples

The following are 14 code examples of bokeh.server.server.Server(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bokeh.server.server , or try the search function .
Example #1
Source File: file_viewer.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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() 
Example #2
Source File: bokeh_webapp.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
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"Open your browser here: http://localhost:{port}")
            server = Server(apps, port=port, io_loop=ioloop)
            if ioloop is None:
                server.run_until_shutdown()
            else:
                server.start()
                ioloop.start() 
Example #3
Source File: BokehServer.py    From BAC0 with GNU Lesser General Public License v3.0 6 votes vote down vote up
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() 
Example #4
Source File: testserver.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _launcher(self, obj, threaded=False, io_loop=None):
        if io_loop:
            io_loop.make_current()
        launched = []
        def modify_doc(doc):
            bokeh_renderer(obj, doc=doc)
            launched.append(True)
        handler = FunctionHandler(modify_doc)
        app = Application(handler)
        server = Server({'/': app}, port=0, io_loop=io_loop)
        server.start()
        self._port = server.port
        self._server = server
        if threaded:
            server.io_loop.add_callback(self._loaded.set)
            thread = threading.current_thread()
            state._thread_id = thread.ident if thread else None
            io_loop.start()
        else:
            url = "http://localhost:" + str(server.port) + "/"
            session = pull_session(session_id='Test', url=url, io_loop=server.io_loop)
            self.assertTrue(len(launched)==1)
            return session, server
        return None, server 
Example #5
Source File: server.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self):
        if hasattr(self, '_target'):
            target, args, kwargs = self._target, self._args, self._kwargs
        else:
            target, args, kwargs = self._Thread__target, self._Thread__args, self._Thread__kwargs
        if not target:
            return
        bokeh_server = None
        try:
            bokeh_server = target(*args, **kwargs)
        finally:
            if isinstance(bokeh_server, Server):
                bokeh_server.stop()
            if hasattr(self, '_target'):
                del self._target, self._args, self._kwargs
            else:
                del self._Thread__target, self._Thread__args, self._Thread__kwargs 
Example #6
Source File: absa_solution.py    From nlp-architect with Apache License 2.0 6 votes vote down vote up
def serve_absa_ui() -> None:
    """Main function for serving UI application.
    """

    def _doc_modifier(doc: Document) -> None:
        grid = _create_ui_components()
        doc.add_root(grid)

    print("Opening Bokeh application on http://localhost:5006/")
    server = Server(
        {"/": _doc_modifier},
        websocket_max_message_size=5000 * 1024 * 1024,
        extra_patterns=[
            (
                "/style/(.*)",
                StaticFileHandler,
                {"path": os.path.normpath(join(SOLUTION_DIR, "/style"))},
            )
        ],
    )
    server.start()
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start() 
Example #7
Source File: ui.py    From nlp-architect with Apache License 2.0 6 votes vote down vote up
def serve_absa_ui() -> None:
    """Main function for serving UI application.
    """

    def _doc_modifier(doc: Document) -> None:
        grid = _create_ui_components()
        doc.add_root(grid)

    print("Opening Bokeh application on http://localhost:5006/")
    server = Server(
        {"/": _doc_modifier},
        websocket_max_message_size=5000 * 1024 * 1024,
        extra_patterns=[
            (
                "/style/(.*)",
                StaticFileHandler,
                {"path": os.path.normpath(join(SOLUTION_DIR, "/style"))},
            )
        ],
    )
    server.start()
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start() 
Example #8
Source File: server.py    From mars with Apache License 2.0 5 votes vote down vote up
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, 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 
Example #9
Source File: apps.py    From parambokeh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bk_worker():
    # Note: num_procs must be 1; see e.g. flask_gunicorn_embed.py for num_procs>1
    server = Server({'/bk_sliders_app': bk_sliders.app},
                    io_loop=IOLoop(),
                    address=bk_config.server['address'],
                    port=bk_config.server['port'],
                    allow_websocket_origin=["localhost:8000"])
    server.start()
    server.io_loop.start() 
Example #10
Source File: run_dashboard.py    From estimagic with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _start_server(apps, port, no_browser, path_to_open):
    """Create and start a bokeh server with the supplied apps.

    Args:
        apps (dict): mapping from relative paths to bokeh Applications.
        port (int): port where to show the dashboard.
        no_browser (bool): whether to show the dashboard in the browser

    """
    # necessary for the dashboard to work when called from a notebook
    asyncio.set_event_loop(asyncio.new_event_loop())

    # 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():
                server.show(path_to_open)

            server.io_loop.add_callback(show_callback)

        address_string = server.address if server.address else "localhost"

        print(
            "Bokeh app running at:",
            f"http://{address_string}:{server.port}{server.prefix}/",
        )
        server._loop.start()
        server.start() 
Example #11
Source File: utils_.py    From kusanagi with MIT License 5 votes vote down vote up
def start_bokeh_server(apps):
    from bokeh.server.server import Server

    s = Server(apps) 
Example #12
Source File: rtl_demo_onescript.py    From pysdr with GNU General Public License v3.0 5 votes vote down vote up
def bkapp_page():
    script = autoload_server(url='http://localhost:5006/bkapp') # switch to server_document when pip uses new version of bokeh, autoload_server is being depreciated
    start_html = '''
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset='utf-8' />
        <meta http-equiv='content-type' content='text/html; charset=utf-8' />
        <title>Streaming with Bokeh Server</title>
      </head>
      <body">'''
    end_html = "</body></html>"   
    return start_html + script + end_html 
Example #13
Source File: pysdr_app.py    From pysdr with GNU General Public License v3.0 5 votes vote down vote up
def create_bokeh_server(self):
        self.io_loop = IOLoop.current() # creates an IOLoop for the current thread
        # Create the Bokeh server, which "instantiates Application instances as clients connect".  We tell it the bokeh app and the ioloop to use
        server = Server({'/bkapp': self.bokeh_app}, io_loop=self.io_loop, allow_websocket_origin=["localhost:8080"]) 
        server.start() # Start the Bokeh Server and its background tasks. non-blocking and does not affect the state of the IOLoop 
Example #14
Source File: server.py    From panel with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def serve(panels, port=0, address=None, websocket_origin=None, loop=None,
          show=True, start=True, title=None, verbose=True, location=True,
          **kwargs):
    """
    Allows serving one or more panel objects on a single server.
    The panels argument should be either a Panel object or a function
    returning a Panel object or a dictionary of these two. If a 
    dictionary is supplied the keys represent the slugs at which
    each app is served, e.g. `serve({'app': panel1, 'app2': panel2})`
    will serve apps at /app and /app2 on the server.

    Arguments
    ---------
    panel: Viewable, function or {str: Viewable or function}
      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=True)
      Whether to print the address and port
    location : boolean or panel.io.location.Location
      Whether to create a Location component to observe and
      set the URL location.
    kwargs: dict
      Additional keyword arguments to pass to Server instance
    """
    return get_server(panels, port, address, websocket_origin, loop,
                      show, start, title, verbose, location, **kwargs)