将Bokeh图嵌入Flask应用程序时出现问题

3

我对Bokeh和Flask都是新手。我浏览了相关的问题、教程,看了Bokeh文档,但仍然无法弄清楚我的错误在哪里。

话虽如此,我想创建一个简单的Web应用程序,其中我可以“组合”各种数据报告和图表。

根据我所读的内容,我想出了以下代码:

app.py:

... # imports

app = Flask(__name__, static_url_path='/static')

@app.route("/")
def index():
  return render_template("index.html")

@app.route("/bokeh_test")
def bokeh_test():

  script, div = components(sample_plot())

  return render_template("bokeh_test.html", script=script, div=div)


def sample_plot():
   """
   A random plot just for testing purposes.
   :return: plot
   """

   PLOT_OPTIONS = dict(plot_width=600, plot_height=400)
   SCATTER_OPTIONS = dict(size=12, alpha=0.5)

   data = lambda: [random.choice([i for i in range(100)]) for r in range(10)]

   plot = figure(sizing_mode='scale_both', tools='pan', **PLOT_OPTIONS)
   plot.scatter(data(), data(), color="red", **SCATTER_OPTIONS)

   # show(plot)

   return plot

bokeh_test.html:

<!DOCTYPE html>
<html lang="en">
 <head>
   <!-- Bokeh includes-->
  <script type="text/javascript" src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.13.min.js"></script>
  <link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.13.min.css" type="text/css" />
  {{ script|safe }}
 </head>
 <body>
   <div>
       <h1>Bokeh sample</h1>
           <div class='bokeh'>
           {{ div|safe }}
           </div>
   </div>
  </body>
</html>

假设在我的index.html文件中,我有一个带链接到bokeh_test.html的侧边栏。当我点击它时,我只看到标题“bokeh样例”,但没有绘图。
如果我取消注释show(plot),就会打开一个新标签,并正确显示绘图,因此问题似乎不在于绘图本身,而是在于我尝试将其嵌入到bokeh_test中的方式。
我对这一切都很新,所以可能我做了些傻事,但是我还没有找到解决方法,希望能得到一些帮助。
附注:不确定是否相关,但为此我从Anaconda 2创建了一个Python 3.6环境,并将此环境用作项目解释器。

1
您正在从CDN加载BokehJS版本0.12.13到您的模板中。这是否是您系统中实际安装的Bokeh版本?它们需要匹配。 - bigreddot
@bigreddot 真准!看来那确实是问题所在!虽然有点傻,但我想知道如果没有你,我还需要多久才能找出来。非常感谢!顺便说一下,我实际上希望从你这里得到答案,因为我看到你基本上成功地回答了我遇到的所有相关问题。 - Tommy
好的,这实际上是一个重复的问题。我知道我在其他地方给出了相同的答案,但我现在无法立即找到先前的问题。但我会在这里添加一个答案。 - bigreddot
1个回答

6

您的模板正在从CDN加载BokehJS 0.12.13版本。该版本必须与系统中安装的Bokeh版本完全匹配


谢谢您将其作为答案添加,我正要建议这样做。再次感谢您的帮助,这真是让人头疼的问题。 - Tommy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接