I have dropdown who’s options are dependent on column in a CSV that get’s updated periodically.
How can I dynamically update the dropdown options when this CSV gets updated? I’ve tried making a callback but it didn’t work and I don’t have a real input for it. I tried messing around some more but to no avail.
Here is my toy code, it refreshes the dataframe correctly, but I can’t get the dropdown options to update as well:
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
import dash_table
from flask_caching import Cache
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
TIMEOUT = 60
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
cache = Cache(app.server, config={
'CACHE_TYPE': 'filesystem',
'CACHE_DIR': 'cache-directory'
})
@cache.memoize(timeout=TIMEOUT)
def query_data():
# This could be an expensive data querying step
df = pd.read_csv('toy.csv')
return df.to_json(date_format='iso', orient='split')
def dataframe():
return pd.read_json(query_data(), orient='split')
# opt = [{'label': i, 'value':i} for i in dataframe()['town'].unique()]
@cache.memoize(timeout=TIMEOUT)
def get_opt():
df = dataframe()
return [{'label': i, 'value':i} for i in df['town'].unique()]
app.layout = html.Div([
dcc.Dropdown(
id='my-dropdown',
options=get_opt(),
value=get_opt()[0]['label']
),
dcc.Tabs(id="tabs", value='tab-1', children=[
dcc.Tab(label='Tab one', value='tab-1'),
dcc.Tab(label='Tab two', value='tab-2'),
]),
html.Div(id='tabs-content')
])
@app.callback(Output('tabs-content', 'children'),
[Input('tabs', 'value'), Input('my-dropdown', 'value')])
def render_content(tab, dropdown):
df = dataframe()
filtered = df[df['town']==dropdown]
if tab == 'tab-1':
return dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in filtered.columns],
data=filtered.to_dict('records')
)
elif tab == 'tab-2':
df2 = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
return dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df2.columns],
data=df2.to_dict('records')
)
if __name__ == '__main__':
app.run_server(debug=True)```