Bokeh 服务器


Bokeh 架构采用解耦设计,其中绘图和字形等对象使用 Python 创建并转换为 JSON 以供 BokehJS 客户端库 .

但是,可以在 python 和浏览器中的对象之间保持同步 Bokeh 服务器 .它可以响应浏览器中生成的用户界面 (UI) 事件,并具有 Python 的全部功能。它还有助于自动将服务器端更新推送到浏览器中的小部件或绘图。

Bokeh 服务器使用 Python 编写的应用程序代码来创建 Bokeh 文档。来自客户端浏览器的每个新连接都会导致 Bokeh 服务器为该会话创建一个新文档。

Server

首先,我们必须开发一个应用程序代码来提供给客户端浏览器。以下代码呈现正弦波线字形。除了绘图之外,还渲染了一个滑块控件来控制正弦波的频率。回调函数 更新数据() updates 列数据源 以滑块的瞬时值作为当前频率的数据。

import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, Text输入
from bokeh.plotting import figure
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data = dict(x = x, y = y))
plot = figure(plot_height = 400, plot_width = 400, title = "sine wave")
plot.line('x', 'y', source = source, line_width = 3, line_alpha = 0.6)
freq = Slider(title = "frequency", value = 1.0, start = 0.1, end = 5.1, step = 0.1)
def update_data(attrname, old, new):
    a = 1
    b = 0
    w = 0
    k = freq.value
    x = np.linspace(0, 4*np.pi, N)
    y = a*np.sin(k*x + w) + b
    source.data = dict(x = x, y = y)
freq.on_change('value', update_data)
curdoc().add_root(row(freq, plot, width = 500))
curdoc().title = "Sliders"

接下来,通过以下命令行启动 Bokeh 服务器:

Bokeh serve –show sliders.py

Bokeh 服务器开始运行并在 localhost:5006/sliders 处为应用程序提供服务。控制台日志显示如下:

C:\Users\User>bokeh serve --show scripts\sliders.py
2019-09-29 00:21:35,855 Starting Bokeh server version 1.3.4 (running on Tornado 6.0.3)
2019-09-29 00:21:35,875 Bokeh app running at: http:// 本地主机:5006/滑块
2019-09-29 00:21:35,875 Starting Bokeh server with process id: 3776
2019-09-29 00:21:37,330 200 GET /sliders (::1) 699.99ms
2019-09-29 00:21:38,033 101 GET /sliders/ws?bokeh-protocol-version=1.0&bokeh-session-id=VDxLKOzI5Ppl9kDvEMRzZgDVyqnXzvDWsAO21bRCKRZZ (::1) 4.00ms
2019-09-29 00:21:38,045 WebSocket connection opened
2019-09-29 00:21:38,049 ServerConnection created

打开你喜欢的浏览器并输入上面的地址。正弦波图显示如下:

ServerConnection

你可以尝试通过滚动滑块将频率更改为 2。

frequency