Bokeh 服务器:使用 FileInput 小部件导入 .csv 文件并将其传递给 ColumnDataSource

Bokeh Server: import .csv file with FileInput widget and pass it to ColumnDataSource

我有一个 csv 文件,其中包含要绘制的数据(x、y 和其他字段),我想使用新的 FileInput 小部件导入它。我没有足够的知识来操作来自 FileInput 的 "base64" 字符串以将其传递给数据框的 ColumnDataSource。

from bokeh.io import curdoc
from bokeh.models.widgets import FileInput

def update_cds(attr, old, new):
    #A code here to extract column names and data
    #from file_input and pass it to a ColumnDataSource or a DataFrame
file_input = FileInput(accept=".csv")
file_input.on_change('value', update_cds)

doc=curdoc()
doc.add_root(file_input)

感谢您的帮助!

Python 有一个内置的 base64 标准库模块:

import base64

data = base64.b64decode(encoded)

这是一个可行的解决方案:代码将在服务器端的 'data' 文件夹(之前创建)中上传 csv 文件。然后很容易打开 csv 并将其传递给 ColumnDataSource。

#widget
file_input = FileInput(accept=".csv")

def upload_csv_to_server(attr, old, new):

    #decode base64 format (from python base24 website)
    base64_message = file_input.value
    base64_bytes = base64_message.encode('ascii')
    message_bytes = base64.b64decode(base64_bytes)
    message = message_bytes.decode('ascii')

    #convert string to csv and save it on the server side
    message_list = message.splitlines()
    with open('data/' + file_input.filename, 'w', newline='') as file:
        writer = csv.writer(file)
        for i in range(len(message_list)):
            writer.writerow(message_list[i].split(','))

file_input.on_change('value', upload_csv_to_server)

如果您看到更好的方法,请告诉我。使用 csv 结构很容易做到这一点,但是任何其他文件格式呢?