ColumnDataSource Download using customJS

Hey,
I’ve tried googling several articles related to this, but still unable to figure why my download script button work. I am not understanding javascript much. Can you guys help me here. The objective is to download the content of columndatasource s3. I’ve attached my code for same. Any trouble shoot method you can recommend?

button_1 = Button(label="Download All", width=300)

download_javaScript="""
function table_to_csv(source) {
    const columns = Object.keys(source.data)
    const nrows = source.get_length()
    const lines = [columns.join(',')]

    for (let i = 0; i < nrows; i++) {
        let row = [];
        for (let j = 0; j < columns.length; j++) {
            const column = columns[j]
            row.push(source.data[column][i].toString())
        }
        lines.push(row.join(','))
    }
    return lines.join('\\n').concat('\\n')
}


var filename = 'results.csv';
var blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
    // Browsers that support HTML5 download attribute
    var url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
}
"""

button_1.js_on_event('tap', CustomJS(args=dict(source=s3), code=download_javaScript)) 

layout = column(p, div, Column(ti), Column(button), Column(table), Column(button_1))

show(layout)

@Nempickaxe If you want someone to try out your code to try to quickly debug it, please make sure it is complete, i.e. it can be copy-pasted into an editor and immediately run without any changes. Really, we also need to know what browser, OS, and package versions are installed. (It’s always advised to provide such details.) Otherwise all I can do is point you to the existing similar example in the repo:

https://github.com/bokeh/bokeh/tree/branch-2.3/examples/app/export_csv

Which, BTW may or may not run on all browsers, I don’t actually know. It was developed and tested on a few, but I seem to recall maybe the “download” code did not work some browser or other. It’s only meant to be a general demonstration of an overall approach that could be the basis for real work.

1 Like