hi
i’m trying to test bokeh for a future project where a document is updated after a asynchronous network service call.In the following example, it is simulated by a asyncio.sleep call.
In the example, the two plots are updated asynchronously after a clicked button, but it seems not. why ?
the code is:
import asyncio
from functools import partial
from random import random
from bokeh.layouts import column, row
from bokeh.models import Button
from bokeh.palettes import RdYlBu3
from bokeh.plotting import figure, curdoc
doc = curdoc()
i = 0
create a callback that adds a number in a random location
async def async_callback(ds, wait):
global i
await asyncio.sleep(wait)
# BEST PRACTICE --- update .data in one step with a new dict
new_data = dict()
new_data['x'] = ds.data['x'] + [random()*70 + 15]
new_data['y'] = ds.data['y'] + [random()*70 + 15]
new_data['text_color'] = ds.data['text_color'] + [RdYlBu3[i%3]]
new_data['text'] = ds.data['text'] + [str(i)]
ds.data = new_data
i = i + 1
def callback(ds, wait):
print(f’wait {wait}’)
doc.add_next_tick_callback(partial(async_callback, ds, wait))
create a plot and style its properties
p = figure(x_range=(0, 100), y_range=(0, 100), toolbar_location=None)
p.border_fill_color = ‘black’
p.background_fill_color = ‘black’
p.outline_line_color = None
p.grid.grid_line_color = None
add a text renderer to the plot (no data yet)
r = p.text(x=, y=, text=, text_color=, text_font_size=“26px”,
text_baseline=“middle”, text_align=“center”)
add a button widget and configure with the call back
button = Button(label=“Press Me with no wait”)
button.on_click(partial(callback, r.data_source, 0))
create a plot and style its properties
p2 = figure(x_range=(0, 100), y_range=(0, 100), toolbar_location=None)
p2.border_fill_color = ‘black’
p2.background_fill_color = ‘black’
p2.outline_line_color = None
p2.grid.grid_line_color = None
add a text renderer to the plot (no data yet)
r2 = p2.text(x=, y=, text=, text_color=, text_font_size=“26px”,
text_baseline=“middle”, text_align=“center”)
button2 = Button(label=“Press Me with wait 10 second”)
button2.on_click(partial(callback,r2.data_source, 10))
put the button and plot in a layout and add to the document
doc.add_root(row(column(button,p), column(button2,p2)))