Bokeh - 服务器

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

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

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

Bokeh 服务器

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

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, TextInput
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://localhost:5006/sliders
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

打开浏览器并输入以上地址。 正弦波图显示如下 −

服务器连接

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

频率