How to export a selected dataframe to an ipynb from a bokeh server

Relevant snippet of code:

def print_datapoints():
    indices = src1.selected.indices
    results = df_final.iloc[indices, :-1]
    results.to_csv(“temp.csv”, mode=‘a’, header=False)

btn = Button(label='Write selected points to CSV', button_type='success')

My current code exports the selected datapoints into temp.csv

Is there a way to automatically create/open an ipynb notebook when the bokeh server starts running and export it as a new dataframe in the notebook whenever the UI button is pressed.

There’s a similar question in the discourse but one of the devs suggested opening a new one due to the thread being old/containing old info.

There’s definitely nothing built in to Bokeh for this, and I can think of quite a few significant obstacles to making anything like this work.

If the Bokeh server is remote, then this is just impossible. The remote server has no ability to open a browser window on your local machine (this has nothing to do with Bokeh, it’s just not possible in general).

If you are just running and viewing the Bokeh app all locally then something like the following step might work.

  • save the CSV
  • programmatically generate a notebook that loads the CSV, and save that too
  • start a Jupyter notebook kernel process for the notebook you saved
  • use the built-in webbrowser module to open a browser to the notebook URL

However, please be aware there are lots of ways this idea could fall completely over in practice:

  • are there even tools for “generating” notebooks? Maybe, but I am not familiar with them
  • have to deal with tedious bookkeeping to prevent filename clashes, randomized ports, etc
  • and also to clean up old kernel processes
  • if the notebook is opened a second time it will require the security token be supplied, seems hard to deal with

And other things too, I am sure. Basically, it’s just sure to be really fragile and likely to be frustrating, which is why we would not try to put anything like this in the Bokeh library itself. But you might be able to cobble together something acceptable for your own purely local experimental/testing purposes, depending on you tolerance for things possibly not working relatively often.

1 Like