如何在Flask和Bokeh中使用AjaxDataSource:
我有一个返回JSON数据的函数:
@app.route("/data", methods=['POST'])
def get_x():
global x, y
x = x + 0.1
y = math.sin(x)
return flask.jsonify(x=[x], y=[y])
我可以毫不费力地在Bokeh的AjaxDataSource中使用它来创建实时流图:
source = AjaxDataSource(data_url="http://localhost:5000/data", polling_interval=1000, mode='append')
p = figure()
p.line('x', 'y', source=source)
show(p)
但是,当我尝试将其嵌入到Flask页面中时,AjaxDataSource无法查询服务器。图表无法呈现且没有错误。请注意,如果我使用静态图而不是AjaxDataSource,则可以正常绘制。以下是相关代码:
template = Template('''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Streaming Example</title>
{{ js_resources }}
{{ css_resources }}
</head>
<body>
{{ plot_div }}
{{ plot_script }}
</body>
</html>
''')
@app.route("/")
def simple():
streaming=True
source = AjaxDataSource(data_url="http://localhost:5000/data",
polling_interval=1000, mode='append')
fig = figure(title="Streaming Example")
fig.line( 'x', 'y', source=source)
js_resources = INLINE.render_js()
css_resources = INLINE.render_css()
script, div = components(fig, INLINE)
html = template.render(
plot_script=script,
plot_div=div,
js_resources=js_resources,
css_resources=css_resources
)
return encode_utf8(html)
如果有任何想法,我将不胜感激。
Brian