通过编辑Bokeh数据表中的单元格来更新SQL数据库?

时间:2019-07-05 21:13:52

标签: python bokeh

我有一个与Bokeh Server应用程序一起运行的仪表板。选项卡之一是数据表,其中包含从SQL数据库中提取的计算机清单(序列号,名称,操作系统等)

我想添加一个可由最终用户编辑的“注释”列,该列将在后台更新SQL表。

我试图遵循以下答案的建议:https://stackoverflow.com/a/49424647/11745820

(我注意到这是Bokeh 0.12.14,我正在运行1.2)

from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, TableColumn, HTMLTemplateFormatter
from bokeh.io import curdoc

# Sample dictionary instead of SQL
dict1 = { 
    'serials':['abc123', 'def456', 'foo123', 'bar456'],
    'names':['computer1', 'computer2', 'computer3', 'computer4'],
    'notes':['']*4
}
source = ColumnDataSource(data=dict1)

columns = [
    TableColumn(field="serials", title="x"),
    TableColumn(field="names", title="y"),
    TableColumn(field="notes", title="serials")
]

data_table = DataTable(
    source=source,
    columns=columns,
    width=800,
    editable=True,
)

# Basic function to demonstrate the problem, but I want this to identify
#if a note was entered and update the SQL table with its contents. 

def on_change_data_source(attr, old, new):
    print(old)
    print(new)

    indices = list(range(len(old['notes'])))
    rows = [(i, j, k) for i, j, k in zip(indices, new['serials'], new['notes'])]
    changes = [x for x in rows if x[2] != ''] # Should be comparing old and new here, but it isn't working. 
    #I can run it as is, but then it would be re-writing all of the notes every single time
    for change in changes:
        print(f'UPDATE computers SET notes={change[2]} WHERE serial={change[1]}')

source.on_change('data', on_change_data_source)

curdoc().add_root(data_table)

我希望上面的代码先打印旧值,然后在更新后打印新值。但是,旧的和新的都显示出“新”的价值。因此,changes始终是一个空列表,没有修补任何内容(我将用SQL更新功能替换该代码)

此外,我想确保只有“注释”列是可编辑的(如果在Bokeh中可以)

0 个答案:

没有答案