I am new to both this forum and the (apparently great) holoviz ecosystem. Apologies if I’m posting to the wrong category (please let me know in this case and I will update the post accordingly).
I am looking for a way to do the following:
I have a Panel app able to plot data that are generated by Python functions. For now these functions are defined on the server side (i.e. the panel app), but I would like that the user can interactively provide her own custom Python functions to this app.
One way to do it would be to allow the user to define a custom function in a jupyter notebook, e.g.:
def f(x):
return 2 * x
Then having a way to send this function definition from the notebook to the Panel app with a syntax like:
To get access the code, the user could upload the notebook via a FileInput widget or just copy the code into the Ace editor widget. If the user uploads a notebook there are python packages that can convert it into a code string.
To execute the code string you can use exec.
Below I provide an example using the Ace editor widget. It would need some more error handling to be robust.
Please note executing user code on your server enables the user to take over or mess with your server!.
import panel as pn
pn.extension("ace", sizing_mode="stretch_width", template="fast", theme="dark")
pn.state.template.title="Code Editor"
CODE = """\
import pandas as pd
import hvplot.pandas
def plot(x):
return pd.DataFrame({
"x": range(x),
"y": [y+x for y in range(x)]
}).hvplot(x="x", y="y")
"""
code = pn.widgets.Ace(value=CODE, language='python', theme="monokai")
x = pn.widgets.IntSlider(name="x", value=5, start=0, end=10, step=1)
@pn.depends(x, code)
def plot(x, code):
d={}
exec(code,d)
if "plot" in d:
return d["plot"](x)
else:
return "plot(x) function not defined"
pn.Column("## Code", code, "## Interactive Plot", x, plot).servable()
panel serve script.py
You could use panel convert ... to convert your app to run in the users browser. Then the users could not execute dangerous code on your server.
Using the Ace editor widget looks like an interesting option. However, i’d like the user to edit the code outside of the server (such as she can e.g. debug it before sending it to the server).
Actually I’m just thinking I could reformulate my question in a more general way. What I am looking for in general is the ability to send data from a client (which in my use case is a jupyter notebook) to the server (which is a Panel application). The data can be for instance numpy arrays ; or functions.
So I am wondering if Panel (or another holoviz lib) is able to handle this natively? Or should I instead encapsulate the Panel app within web server such as Flask? In the second case, is there a web server library which is recommend to be used with the holoviz ecosystem? (e.g. Flask?).