如何将独立散景图嵌入到django模板中

Gha*_*kfa 31 django django-templates python-2.7 bokeh

我想通过django框架在我的Web应用程序中显示散景库提供的图形,但我不想使用散景服务器可执行文件,因为它不是好方法.那有可能吗?如果是的话怎么做?

iMi*_*twe 52

使用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})
Run Code Online (Sandbox Code Playgroud)

urls.py我们可以放的文件中:

from myapp.views import simple_chart 
...
...
...
url(r'^simple_chart/$', simple_chart, name="simple_chart"),
...
...
Run Code Online (Sandbox Code Playgroud)

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> 
Run Code Online (Sandbox Code Playgroud)

它有效.

  • 感谢您将建议付诸实践!实际上,添加一些"如何在{whatever_web_framework}中嵌入我的散景图?" 文档或某处的部分可能是一个很好的补充.如果您想帮助解决这个问题,请提出一个问题供讨论或者PR添加这种示例请随意这样做.非常感谢!谢谢! (6认同)

Fab*_*ger 5

您不需要使用散景服务器来嵌入散景图.它只是意味着你不会使用(也可能不需要)它提供的额外功能.

事实上,您可以通过多种方式嵌入散景图,例如生成独立的html,生成散景独立组件,然后您可以在渲染模板时嵌入您的django应用程序或使用我们称之为"自动加载"的方法,这使得散景返回将替换的标签本身有一个散景图.您可以在文档中找到更好的详细信息.

另一个很好的灵感来源是您可以在存储库中找到的嵌入示例.