Search code examples
pythonbokehtornado

Access static directory when using Bokeh as a library


I am trying to make a bokeh server that servers the same view to all people connecting. I have been able to achieve this using the Bokeh in library mode using the following code:

from tornado.ioloop import IOLoop
from bokeh.server.server import Server
from bokeh.plotting import curdoc

io_loop = IOLoop.current()
server = Server(applications={'/myapp': self.make_document},
                io_loop=io_loop,
                allow_websocket_origin=['{0}.com:5001'.format(
                    hostname.lower()), 'localhost:5001'],
                port=5001,
                )
  
server.start()
server.show('/myapp')
io_loop.start()

Run with python main.py, but I cannot access the static directory /myapp/static.

If I instead do:

self.make_document(curdoc())

And start myapp using bokeh server --show myapp I can access static just fine, but each new browser tab connecting gets a new view.

Is there a way to access static in library mode? Or a way to serve the same view to all connecting and still use bokeh document mode.


Solution

  • Found answer in Bokeh Tornado Embed Example

    from tornado.web import StaticFileHandler
    from tornado.ioloop import IOLoop
    from bokeh.server.server import Server
    from bokeh.plotting import curdoc
    
    io_loop = IOLoop.current()
    server = Server(applications={'/myapp': self.make_document},
                    io_loop=io_loop,
                    allow_websocket_origin=['{0}.com:5001'.format(
                        hostname.lower()), 'localhost:5001'],
                    port=5001,
                    extra_patterns=[
                        (r'/mydir/(.*)', StaticFileHandler, {'path': 
                        os.path.normpath(os.path.dirname(__file__) + '/mydir')})],
                    )
      
    server.start()
    server.show('/myapp')
    io_loop.start()
    

    Here the mydir needs to be in the myapp directory and not the parent one.