按复杂程度排序,使用 Pyramid ,我可以创建静态 Bokeh 图,然后将它们与 div 标签合并,如概述 here .
Bokeh documentations清楚地解释如何设置 Bokeh 服务器以进行交互式数据探索,我已经成功创建了这样一个应用程序。
但我想做的是在 Pyramid View 页面中有一个交互式图表。此页面的要求如下:
- 加载 View 后,以某种方式启动 Bokeh 服务器,并将数据加载到服务器的对象模型中。
- Pyramid View 也会以某种方式接收服务器对象模型中的数据并呈现数据。
有些事情我不清楚:
- 我不确定应该在哪里呈现用于选择和过滤数据的“小部件”。看起来为了与图形的其余部分轻松交互,它们应该是 Bokeh 服务器的一部分。
- 我不确定如何将 Bokeh 服务器页面集成到 Pyramid View 中。
- 我也不确定如何从 Pyramids 网络应用中启动 Bokeh 服务器。
有one paragraph其中提到如何将 Bokeh 服务器嵌入到 Flask 或 Tornado 应用程序中。但是这段太简短了,我现在无法理解。所以我问我如何在 Pyramid 中做到这一点?
请您参考如下方法:
作为bigreddot据说,工作流程与代码中的微小更改非常相似。我实际上根据他的回答建立了我的答案。感谢大红点!
以下是我将 bokeh-server 与 Pyramid 集成的解决方案。
- 创建一个函数来生成 Bokeh 文档(绘图)
def bokeh_doc(doc):
# create data source
# define all elements that are necessary
# ex:
p = line(x, y, source)
# now add 'p' to the doc object
doc.add_root(p)
# define a callback if necessary
# and register that callback
doc.add_periodic_callback(_cb, delay)
- 将应用程序的路由位置添加到 Pyramid 服务器配置对象。 主要在
__init__.py或您配置路由的任何其他文件中。
conf.add_route('bokeh_app', '/bokeh-app')
- 添加一个必须呈现
bokeh_app的 View 。此函数可以写在views.py或您认为合适的任何地方。
from pyramid.view import view_config
from bokeh.embed import server_document
@view_config(route_name='bokeh_app', renderer='static/plot.jinja2')
def bokeh_view(request):
# this '/app' route to the plot is configured in step. 4
# using default host and port of bokeh server.
# But, the host and port can be configured (step. 4)
script = server_document('localhost:5006/app')
# assuming your jinja2 file has
# {{ script|safe }}
# embedded somewhere in the <body> tag
return {'script': script}
- 现在,启动 Bokeh 服务器。
from bokeh.application import Application
from bokeh.application.handlers import FunctionHandler
from bokeh.server.server import Server
# bokeh_doc is the function which defines the plot layout (step. 1)
chart_app = Application(FunctionHandler(bokeh_doc))
# the '/app' path is configured to display the 'chart_app' application
# here, a different host and port for Bokeh-server could be defined
# ex: {"<host2:9898>/app_bokeh": chart_app}
bokeh_server = Server({"/app": chart_app}, allow_websocket_origin=["localhost:6543"])
# start the bokeh server and put it in a loop
server.start()
server.io_loop.start()
allow_websocket_origin 接收必须升级以支持 bokeh 所需的网络套接字连接的字符串列表。在这种情况下,我们需要提供 Pyramid 服务器的 url
- 最后,启动 Pyramid 服务器
from wsgiref.simple_server import make_server
pyramid_app = conf.make_wsgi_app()
pyramid_server = make_server('localhost', 6543, pyramid_app)
pyramid_server.serve_forever()
