定期回调引发的散景错误

Bokeh Error thrown from periodic callback

我正在学习关于 Bokeh 的 Udemy 教程,我遇到了一个我不知道如何解决的错误,并且没有收到导师的回复。起初,我以为我的代码有问题,所以花了大约一个星期的时间试图弄清楚,最后放弃并复制导师的代码才发现错误仍然存​​在。

代码的目的是抓取和绘制实时数据。代码如下:

from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, DatetimeTickFormatter
from bokeh.plotting import figure
from random import randrange
import requests
from bs4 import BeautifulSoup

# Create the figure
f = figure()

# Create webscraping function
def extract_value():
    r = requests.get("https://bitcoincharts.com/markets/okcoinUSD.html", headers = {'User-Agent' : 'Chrome'})
    c = r.content
    soup = BeautifulSoup(c, "html.parser")
    value_raw = soup.find_all("p")
    value_net = float(value_raw[0].span.text)
    return value_net

# Create ColumnDataSource
source = ColumnDataSource(dict(x = [], y = []))

# Create glyphs
f.circle(x = 'x', y = 'y', color = 'olive', line_color = 'brown', source = source)
f.line(x = 'x', y = 'y', source = source)

# Create periodic funtion
def update():
    new_data = dict(x = [source.data['x'][-1]+1], y = [extract_value])
    source.stream(new_data, rollover = 200)
    print(source.data) # Displayed in the commmand line!

# Add a figure to curdoc and configure callback
curdoc().add_root(f)
curdoc().add_periodic_callback(update, 2000)

哪个是投掷:

Error thrown from periodic callback: IndexError('list index out of range',)

对这里发生的事情有什么想法吗?

像这样更改您的更新函数:

# Create periodic funtion
def update():
    if len(source.data['x']) == 0:
        x = 0
    else:
        x = source.data['x'][-1]+1

    new_data = dict(x = [x] , y = [extract_value()])
    print("new_data", new_data)
    source.stream(new_data, rollover = 200)
    print(source.data) # Displayed in the commmand line!

您的代码有两个问题:

  1. 您不调用 extract_value 函数,而只是将其分配给y。因此,y 将不包含返回值。
  2. source.data['x'] 是第一次调用 update() 时的空列表。因此,您尝试访问空列表的最后一个元素(通过 [-1])。这给你错误 IndexError('list index out of range')

1 的解决方案很简单。对于 2,它类似于您之前尝试执行的操作。但首先检查 source.data['x'] 是否为空。这将是第一次调用更新时的情况。在那里,您将 x 设置为 0。在接下来的执行中,当列表非空时,您获取列表中的最后一个值并将其递增 1。