Skip to content

Instantly share code, notes, and snippets.

@aidanhmiles
Last active November 8, 2020 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aidanhmiles/39b0acc8945ae7569a18914ab4b632db to your computer and use it in GitHub Desktop.
Save aidanhmiles/39b0acc8945ae7569a18914ab4b632db to your computer and use it in GitHub Desktop.
This Python script demonstrates how to run analyses on user-submitted data files using Panel. It runs a Holoviz Panel webpage with a single Plotly line chart which is fed by a FileInput that accepts only CSVs.
# python 3.7+
# install dependencies:
# pip install panel pandas plotly
# run it: panel serve --show thisfile.py
import io
import param
import panel as pn
import pandas as pd
import plotly.express as px
class FileInputDemo(param.Parameterized):
data = param.DataFrame()
file_input = param.Parameter()
def __init__(self, **params):
# set the default state of the file_input param
# must go before super() for some reason
self.param.file_input.default = pn.widgets.FileInput(accept=".csv")
super().__init__(**params)
# initialize data_pane as a DataFrame pane with an empty pandas DataFrame
self.data_pane = pn.pane.DataFrame(pd.DataFrame())
# initialize chart_pane as an empty Plotly chart
self.chart_pane = pn.pane.Plotly()
# initialize the str_pane with a string
self.str_pane = pn.pane.Str("No file uploaded")
# executed when file_input.value changes, i.e. a file is selected
@param.depends("file_input.value", watch=True)
def _parse_file_input(self):
# get the byte value of the file
value = self.file_input.value
# get the file's filename
self.filename = self.file_input.filename
# decode it using StringIO
string_io = io.StringIO(value.decode("utf8"))
# set self.data to the csv contents of the input
self.data = pd.read_csv(string_io)
@param.depends("data", watch=True)
def _update_(self):
print("self.data")
print(self.data)
# update all panes
# str_pane can indicate that a file was uploaded
self.str_pane.object = "File selected: {}".format(self.filename)
# self.str_pane.object = "File selected"
# don't replace data_pane, but update its object with a new DataFrame pane object
self.data_pane.object = pn.pane.DataFrame(self.data).object
# branch off into other methods if you want
self._secondary_update_method()
def _secondary_update_method(self):
# update chart_pane with a new plotly line chart with the new CSV data
self.chart_pane.object = px.line(self.data)
def panel(self):
# create a Column out of the file input the 3 panes
return pn.Column(
self.file_input, self.str_pane, self.data_pane, self.chart_pane
)
panel = FileInputDemo().panel()
panel.servable()
A B C
1 2 3
3 2 1
2 2 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment