如何将独立的Bokeh图表嵌入Django模板

31

我想通过Django框架在我的Web应用程序中显示Bokeh库提供的图表,但我不想使用bokeh-server可执行文件,因为这不是好的方式。那么这是可能的吗?如果是,如何做到呢?

5个回答

53

按照Fabio Pliger的建议,使用Embedding Bokeh Plots文档示例,我们可以在Django中执行以下操作:

views.py文件中,我们放置:

from django.shortcuts import render
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components

def simple_chart(request):
    plot = figure()
    plot.circle([1,2], [3,4])

    script, div = components(plot, CDN)

    return render(request, "simple_chart.html", {"the_script": script, "the_div": div})

urls.py文件中,我们可以放置以下代码:

from myapp.views import simple_chart 
...
...
...
url(r'^simple_chart/$', simple_chart, name="simple_chart"),
...
...

在模板文件simple_chart.html中,我们将有:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Experiment with Bokeh</title>
    <script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
    <link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">
</head>
<body>

    {{ the_div|safe }}

    {{ the_script|safe }}
</body>
</html> 

它有效。


6
感谢你将建议付诸实践!实际上,在文档或其他地方添加一些“如何将我的 bokeh 图形嵌入 {任何网络框架}?”的说明,可能会是一个很好的补充。如果你想协助完成这个任务,请提交一个讨论问题的 issue 或者一个添加此类示例的 PR,不胜感激!谢谢! - Fabio Pliger
1
如果您将脚本和CSS的版本更改为0.11.1,它也可以与Bokeh 0.11.1一起使用。 - Barney Szabolcs
1
如果你只看到一个白屏,并且在浏览器控制台中看到“TypeError: Bokeh.safely is not a function”,那么请参考:https://dev59.com/4KHia4cB1Zd3GeqPPjP7 - pjdavis

5
你不需要使用bokeh-server来嵌入bokeh图表,这意味着你不会使用(并且可能不需要)它提供的额外功能。
实际上,你可以通过多种方式嵌入bokeh图表,例如生成独立的html,通过生成bokeh独立组件,当渲染模板时在django应用程序中嵌入它们,或使用我们称之为“自动加载”的方法,该方法使bokeh返回一个标签,它将用Bokeh图表替换自身。你可以在文档中找到更好的详细信息。
另一个灵感的好来源是仓库中可以找到的嵌入示例

3

还可以通过AJAX请求来实现它的工作。假设我们已经加载了一个页面,想要在不重新加载整个页面的情况下在按钮单击时显示绘图。从Django视图中,我们以JSON格式返回Bokeh脚本和div:

from django.http import JsonResponse
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components

def simple_chart(request):
  plot = figure()
  plot.circle([1,2], [3,4])

  script, div = components(plot, CDN)

  return JsonResponse({"script": script, "div": div})

当我们在 JS 中获取 AJAX 响应时(本例使用 Jquery),div 首先被附加到现有页面,然后将脚本附加:

$("button").click(function(){
  $.ajax({
    url: "/simple_chart", 
    success: function(result){
      var bokeh_data = JSON.parse(result);
      $('#bokeh_graph').html(bokeh_data.div);
      $("head").append(bokeh_data.script);
  }});
});

这对我很有效,但我不得不删除JSON.parse()。 - Saleem Khan

2

必须将{{the_script | safe}}放在head标签内部


2
你可以在任何地方输入,甚至在页面的页脚。 - iMitwe
为了提高用户体验并减少页面加载时间,将其放在页脚可能更好。 - negstek

1
这是一个使用jquery与bokeh绘图交互的flask应用程序。查看templates/以获取可重用的javascript代码。还可以在github上搜索bokeh-demos。

1
链接已失效。 - Jonathan
似乎bokeh删除了他们的bokeh-demos存储库。但是其他人已经创建了类似的存储库。这个存储库是使用flask和jquery的ajax演示:https://github.com/kgullikson88/bokeh-demos/tree/stocks_demo/stocks - hobs

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