Flask App 中的散景问题渲染图

Bokeh Problem Rendering Plot in Flask App

我的烧瓶驱动的应用程序与 Bokeh 的高级条形图一起按预期工作。

我现在想将绘图更改为水平条形图并找到了 this SO 答案。

为简洁起见,我的代码去掉了格式:

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
            )

位于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>

此答案适用于 show(p) 的测试。然而,实际应用程序采用 p 对象并获取组件 divscript 并将它们嵌入 html 中。

当我 运行 带有 debug=True 的应用程序时,我没有收到错误,只是一个挂起的页面。

编辑:"Hang" 不准确。我得到一个空白页。

按照 Bigreddot 的建议,我检查了我的 Bokeh 版本并调整了 BokehJS 版本以匹配。

conda list bokeh 产出:

bokeh                     0.10.0                   py27_0  

然后我更改了我的 html,最小示例按预期工作。

<!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>

如果有人从现在开始遇到这个问题,请注意 bokeh.util.string import encode_utf8 自 bokeh==2.0.0

以来已被删除

在我的例子中,使用 flask 应用程序(使用 flask==1.1.2 和 bokeh==2.0.2),我可以简单地从代码和 html 渲染中删除这一行模板,只是 return html 而不是 return encode_utf8(html).