在Flask中嵌入散景图

时间:2015-10-31 10:58:00

标签: javascript python flask bokeh

我期待得到Flask返回的一个简单的散景图,但是当我浏览到localhost时我得到的是:5002 / simpleline是这样的:

('',' “)

我有两个文件。 Python文件:

from bokeh.plotting import figure, show, output_file
from bokeh.embed import components
from flask import Flask, render_template
app=Flask(__name__)

@app.route('/simpleline/')
def simpleLine():
    fig=figure(title="Sensor data")
    fig.line([1,2,3,4],[2,4,6,8])
    div=components(fig)
    return render_template('simpleline.html',div=div)
    show(fig)

if __name__ == "__main__":
    app.run(debug=True,port=5002)

HTML模板:

<!doctype html>
<html>
<head>
 <title>Figure examples</title>
 <link rel="stylesheet" href="http://cdn.pydata.org/bokeh-0.7.1.min.css" type="text/css" />
 <script type="text/javascript"src="http://cdn.pydata.org/bokeh-0.7.1.min.js"></script>
</head>
<body>
<div class='bokeh'>
 {{ div|safe }}
</div>
</body>
</html>

我确信我在这里缺少必要的东西。

在mn的回答之后,发现components()产生了两个元素,一个Javascript字符串和一个html div。所以,我按如下方式更新了我的脚本,但这次网页显示为空白。

from bokeh.plotting import figure, show, output_file
from bokeh.embed import components
from flask import Flask, render_template
app=Flask(__name__)

@app.route('/simpleline/')
def simpleLine():
    fig=figure(title="Sensor data")
    fig.line([1,2,3,4],[2,4,6,8])
    global script
    global div
    script,div=components(fig)
    return render_template('simpleline.html',div=div,script=script)
    output_file("simpleline.html")
    show(fig)

fig=figure(title="Sensor data")
fig.line([1,2,3,4],[2,4,6,8])
script,div=components(fig)
if __name__ == "__main__":
    app.run(debug=True,port=5002)

HTML模板:

<!doctype html>
<html>
 <head>
  <title>Figure examples</title>
  <link rel="stylesheet" href="http://cdn.pydata.org/bokeh-0.9.0.min.css" type="text/css" />
  <script type="text/javascript" src="http://cdn.pydata.org/bokeh-0.9.0.min.js"></script>
  {{ script|safe }}
 </head>
 <body>
  <div class='bokeh'>
   {{ div|safe }}
  </div>
 </body>
</html>

我尝试了所有的散景-0.7.1.min.js,0.9和0.10,但我仍然有相同的空白页。

2 个答案:

答案 0 :(得分:5)

components()返回带有(script, div)的{​​{1}}元组,其中包含您的绘图数据以及加载了绘图视图的随附<script>标记:http://bokeh.pydata.org/en/0.10.0/docs/user_guide/embed.html#components

<div>

模板

script, div = components(fig)
return render_template('simpleline.html',div=div, script=script)

答案 1 :(得分:2)

或者,如果您希望自动加载散景js和css,也可以使用autoload_static代替components。您还可以将js保存到文件路径中,并仅使用html中的div来访问它。

以下是我使用的示例代码:

from bokeh.embed import autoload_static
from bokeh.resources import CDN
.............
.............
js, div = autoload_static(bar, CDN, '/static/bokeh/plot.js')
with open('static/bokeh/plot.js', 'w') as f:
        f.write(js)

然后在html文件中只包含div标签(包括js脚本的路径)。

<!doctype html>
 <html>
   <head>
     <title>Figure examples</title>
   </head>
   <body>
    <div class='bokeh'>
    {{ div|safe }}
    </div>
   </body>
 </html>