Search code examples
pythonflaskbokeh

Bokeh Problem Rendering Plot in Flask App


My flask driven app works as expected with the high level Bar plot from Bokeh.

I now want to change the plot to a horizontal bar plot and found this SO answer.

My code minus the formatting for brevity:

from flask import Flask, render_template
from bokeh.embed import components
from bokeh.util.string import encode_utf8
from bokeh.plotting import figure
import pandas as pd

app = Flask(__name__)

@app.route('/')
def test():
    kws = ["one", "two", "cat", "dog"]
    count = [23, 45, 11, 87]
    df = pd.DataFrame({"kw": kws,
                       "count": count
                       })

    df.sort("count", inplace=True)
    df.set_index("kw", inplace=True)
    series = df['count']

    p = figure(width=1000, height=1000, y_range=series.index.tolist())

    j = 1
    for k, v in series.iteritems():
        w = v / 2 * 2
        p.rect(x=v/2,
                y=j,
                width=w,
                height=0.4,
                color=(76, 114, 176),
                width_units="screen",
                height_units="screen"
                )
        j += 1

    #### get components ####
    script, div = components(p)

    page = render_template('test.html', div=div, script=script)
    return encode_utf8(page)


if __name__ == "__main__":
    app.run(debug=True,
            threaded=False
            )

Located in templates/test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.9.0.min.css" rel="stylesheet" type="text/css">
    <script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.9.0.min.js"></script>
</head>

<body>

{{ div | safe }}
{{ script | safe }}

</body>
</html>

This answer works in testing with show(p). However the actual application takes the p object and gets the components div and script and embeds those in html.

When I run the app with debug=True I do not get an error just a hanging page.

EDIT: "Hang" is not accurate. I get a blank page.


Solution

  • Following Bigreddot's advice, I checked my version of Bokeh and adjusted the BokehJS version to match.

    conda list bokeh yielded:

    bokeh                     0.10.0                   py27_0  
    

    I then changed my html and the minimal example works as expected.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.css" rel="stylesheet" type="text/css">
        <script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.js"></script>
    </head>
    
    <body>
    
    {{ div | safe }}
    {{ script | safe }}
    
    </body>
    </html>