我想使用散景在django中实现实时图形。我尝试了很多方法,但没有任何方法可以帮助我。我得到的代码工作正常bokeh serve
但在django中不起作用。任何人都可以帮助我吗?我被困了差不多一个星期。代码如下:
import numpy as np
from bokeh.client.session import push_session
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
import random
from bokeh.embed import components
# 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
# p.border_fill_color = 'black'
# p.background_fill_color = 'black'
# p.outline_line_color = None
# p.grid.grid_line_color = None
# add a text renderer to out plot (no data yet)
r = p.line(x = [], y = [], legend='close', color='navy')
s = p.triangle(x = [], y = [], legend='sell', color='red' ,size=10 )
t = p.triangle(x = [], y = [], legend='buy', color='green' ,size=10 )
# r = p.text(x=[], y=[], text=[], text_color=[], text_font_size="20pt",
# text_baseline="middle", text_align="center")
i = 0
dr = r.data_source
ds = s.data_source
dt = t.data_source
# create a callback that will add a number in a random location
def callback():
global i
a=fxdata()[0]
val = np.random.random()*70 + 15
dr.data['x'].append(i) # np.datetime64(str(a[1]))
dr.data['y'].append( val ) # np.float(a[2])
rm = random.randint(1,10)
if rm <= 2:
ds.data['x'].append(i) # np.datetime64(str(a[1]))
ds.data['y'].append(val)
elif rm >=9 :
dt.data['x'].append(i) # np.datetime64(str(a[1]))
dt.data['y'].append(val)
else:
pass
# ds.data['text_color'].append(RdYlBu3[i%3])
# ds.data['text'].append(str("MJ"))
dr.trigger('data', dr.data, dr.data)
ds.trigger('data', ds.data, ds.data)
dt.trigger('data', dt.data, dt.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)
我尝试使用随机数进行简单的实时绘图。我想在django做同样的事情。谁能帮我?帮助将不胜感激。
答案 0 :(得分:0)
如果您要在与Django应用程序相同的进程中运行Bokeh服务器,即您不想运行单独的bokeh serve
进程并使用server_document
将其嵌入到Django应用程序中,则您将必须embed the Bokeh server as a library。
def modify_doc(doc):
# set up app here, use doc.add_root(...)
def bk_worker():
# Can't pass num_procs > 1 in this configuration. If you need to run multiple
# processes, see e.g. flask_gunicorn_embed.py
server = Server({'/bkapp': modify_doc}, io_loop=IOLoop(), allow_websocket_origin=["localhost:8000"])
server.start()
server.io_loop.start()
from threading import Thread
Thread(target=bk_worker).start()
然后,您将获得一个脚本以通常的方式嵌入应用程序:
script = server_document('http://localhost:5006/bkapp')
,并将其包含在应嵌入应用程序的页面模板中。