Skip to main content
 首页 » 编程设计

python之如何在 Django 中使用 Bokeh add_periodic_callback 函数

2025年01月19日34zengkefu

我正在尝试在 Django 中实现 Bokeh 实时图表。我在一个网站上得到了一些引用。他们使用 curdoc() 中的 add_periodic_callback 函数来刷新图表。通过运行 bokeh serve filename.py 可以正常工作。我通过在我的 view.py

中使用这段代码在 django 中尝试了这个
def bokeh(request): 
    import numpy as np 
    from bokeh.layouts import column 
    from bokeh.models import Button 
    from bokeh.palettes import RdYlBu3 
    from bokeh.plotting import figure, curdoc 
    import pandas as pd         
 
    # create a plot and style its properties 
    p = figure(x_axis_type="datetime", title="EUR USD", plot_width=1000) 
    p.grid.grid_line_alpha = 0 
    p.xaxis.axis_label = 'Date' 
    p.yaxis.axis_label = 'Price' 
    p.ygrid.band_fill_color = "olive" 
    p.ygrid.band_fill_alpha = 0.1 
 
 
 
    # add a text renderer to out plot (no data yet) 
    r = p.line(x = [], y = [], legend='close', color='navy') 
 
    i = 0 
 
    ds = r.data_source 
 
    # create a callback that will add a number in a random location 
    def callback(): 
        global i 
        a = fxdata()[0] ## this script will return EURUSD forex data as list 
 
        ds.data['x'].append(np.datetime64(str(a[1])))  
        ds.data['y'].append(np.float(a[2]))     
 
        ds.trigger('data', ds.data, ds.data) 
        i = i + 1 
 
    # add a button widget and configure with the call back 
    button = Button(label="Press Me") 
    # button.on_click(callback) 
 
    # put the button and plot in a layout and add to the document 
    curdoc().add_root(column(button, p)) 
    curdoc().add_periodic_callback(callback, 1000) 
    script, div = components(curdoc()) 
 
    return render_to_response( 'bokeh/index.html', {'script' : script , 'div' : div} )   

当我尝试此代码时,输​​出的是空的 Bokeh 图框架。我们可以通过在 Django 中使用 add_periodic_callback 函数来做到这一点吗?或任何其他类似的方式来刷新图表。

谁能帮帮我。如果你觉得它不明白,请在这里评论。 您的帮助将不胜感激。提前致谢。

请您参考如下方法:

我认为你可以使用嵌入式服务器文档:

from bokeh.embed import server_document 
script = server_document("https://demo.bokeh.org/slider") 

这会输出一个 <script></script>您可以嵌入到文档中的 Bokeh 服务器页面。

来源: https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#app-documents