Search code examples
dataframefile-iowidgetbokeh

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


I have a csv file with my data to plot (x, y, and other fields) and want to import it using the new FileInput widget. I don't have sufficient knowledge to manipulate the "base64" strings coming from FileInput to pass it to a ColumnDataSource of dataframe.

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)

Thanks for your help!


Solution

  • Here is a working solution: the code will upload the csv file on the server side in a 'data' folder (to be created before). Then it is easy to open the csv and pass it to a ColumnDataSource for instance.

    #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)
    

    If you see a nicer way please let me know. It is easy with the csv structure to do that way but what about any other file format?