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

2024-06-16 10:46:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想添加一个可以由最终用户编辑的“Notes”列,它将在后台更新SQL表。你知道吗

我试着听从这个答案的建议:https://stackoverflow.com/a/49424647/11745820

(我注意到这是为博基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 update函数替换该代码)

另外,我想确保只有“notes”列是可编辑的(如果在Bokeh中可能的话)


Tags: columnsfromimportfieldsourcenewsqldata