Bokeh 服务器 API#

将Bokeh服务器嵌入到更大的Tornado应用程序或Jupyter笔记本中,并使用现有的Tornado IOloop 可能会很有用。以下是Bokeh在这种场景下集成的基础:

from bokeh.server.server import Server

server = Server(
    bokeh_applications,  # list of Bokeh applications
    io_loop=loop,        # Tornado IOLoop
    **server_kwargs      # port, num_procs, etc.
)

# start timers and services and immediately return
server.start()

你也可以直接创建和控制一个IOLoop。这在创建独立的“普通”Python脚本以服务Bokeh应用程序或将Bokeh应用程序嵌入到如Flask或Django等框架中时非常有用,而无需运行单独的Bokeh服务器进程。你可以在示例目录中找到一些这种技术的示例:

还要注意,bokeh serve 的每个命令行参数都有一个对应的 Server 关键字参数。例如,使用 --allow-websocket-origin 命令行参数等同于传递 allow_websocket_origin 作为参数。

使用 bokeh.client 进行连接#

您可以通过客户端API直接与Bokeh服务器交互,该API可用于在Bokeh服务器上的现有会话中修改Bokeh文档。

../../../_images/bokeh_serve_client.svg

通常,网络浏览器连接到Bokeh服务器,但你可以通过使用bokeh.client模块从Python建立连接。#

这可能很有用,例如,可以对由另一个Web框架(如Flask或Django)嵌入的Bokeh应用程序进行用户特定的定制。在以下示例中,Flask端点嵌入了已经在服务器上运行的“滑块”应用程序,但在将输出传递给用户之前更改了绘图标题之前

from flask import Flask, render_template

from bokeh.client import pull_session
from bokeh.embed import server_session

app = Flask(__name__)

@app.route('/', methods=['GET'])
def bkapp_page():

    with pull_session(url="http://localhost:5006/sliders") as session:

        # update or customize that session
        session.document.roots[0].children[1].title.text = "Special sliders for a specific user!"

        # generate a script to load the customized session
        script = server_session(session_id=session.id, url='http://localhost:5006/sliders')

        # use the script in the rendered page
        return render_template("embed.html", script=script, template="Flask")

if __name__ == '__main__':
    app.run(port=8080)