Bhanuday Birla
Bhanuday Birla

Reputation: 1039

How can we embed bokeh layout objects (containing multiple plots and widgets) inside flask app?

I have a bokeh layout/curr_doc object and i want to embed it into flask app. I can embed all plots and widgets component wise but as a single layout i don't find any reference anywhere.The reason i want to embed full layout is that this will preserve the interactivity between plots and widgets.

Upvotes: 1

Views: 447

Answers (1)

ChesuCR
ChesuCR

Reputation: 9630

Check the following example, it is in the examples folder in the GH project. You can check for more examples related to embedding here. You can also create an iframe and include all your application inside (though usually it is heavier for the browser). Check the bryan answer here as well, but take into account that in the latest bokeh versions you should use server_document instead of autoload_server as this example shows:

import atexit
import subprocess

from flask import render_template_string, Flask
from bokeh.embed import server_document

home_html = """
<!DOCTYPE html>
<html lang="en">
  <body>
    <div class="bk-root">
      <h1><a href="/batch/1"> Batch 1 (cos)</a></h1>
      <h1><a href="/batch/2"> Batch 2 (sin)</a></h1>
      <h1><a href="/batch/3"> Batch 3 (tan)</a></h1>
    </div>
  </body>
</html>
"""

app_html = """
<!DOCTYPE html>
<html lang="en">
  <body>
    <div>
        <h2><a href="/batch/1">Batch 1 (cos)</a> - <a href="/batch/2">Batch 2 (sin)</a> - <a href="/batch/3">Batch 3 (tan)</a></h2>
    </div>
    {{ bokeh_script|safe }}
  </body>
</html>
"""

app = Flask(__name__)

bokeh_process = subprocess.Popen(
    ['python', '-m', 'bokeh', 'serve', '--allow-websocket-origin=localhost:5000', 'bokeh_server.py'], stdout=subprocess.PIPE)

@atexit.register
def kill_server():
    bokeh_process.kill()

@app.route('/')
def home():
    return render_template_string(home_html)

@app.route('/batch/<int:batchid>')
def visualization(batchid):
    bokeh_script = server_document(url='http://localhost:5006/bokeh_server', arguments=dict(batchid=batchid))
    return render_template_string(app_html, bokeh_script=bokeh_script)

if __name__ == '__main__':
    app.run(debug=True)

Upvotes: 1

Related Questions