Reputation: 13
I am new to python and plotly-dash. I am trying to use "Hidden Div" to store a data frame as suggested in dash tutorial 5. But I am not able to process the uploaded file.
import base64
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
#global_df = pd.read_csv('...')
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Graph(id='graph'),
html.Table(id='table'),
dcc.Upload(
id='datatable-upload',
children=html.Div(['Drag and Drop or ',html.A('Select Files')]),
),
# Hidden div inside the app that stores the intermediate value
html.Div(id='intermediate-value', style={'display': 'none'})
])
def parse_contents(contents, filename):
content_type, content_string = contents.split(',') #line 28
decoded = base64.b64decode(content_string)
if 'csv' in filename:
# Assume that the user uploaded a CSV file
return pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
return pd.read_excel(io.BytesIO(decoded))
elif 'xlsx' in filename:
# Assume that the user uploaded an excel file
return pd.read_excel(io.BytesIO(decoded))
@app.callback(Output('intermediate-value', 'children'),
[Input('datatable-upload', 'contents')],
[State('datatable-upload', 'filename')])
def update_output(contents, filename):
# some expensive clean data step
cleaned_df = parse_contents(contents, filename)
# more generally, this line would be
# json.dumps(cleaned_df)
return cleaned_df.to_json(date_format='iso', orient='split')
@app.callback(Output('graph', 'figure'), [Input('intermediate-value', 'children')])
def update_graph(jsonified_cleaned_data):
# more generally, this line would be
# json.loads(jsonified_cleaned_data)
dff = pd.read_json(jsonified_cleaned_data, orient='split')
figure = create_figure(dff)
return figure
@app.callback(Output('table', 'children'), [Input('intermediate-value', 'children')])
def update_table(jsonified_cleaned_data):
dff = pd.read_json(jsonified_cleaned_data, orient='split')
table = create_table(dff)
return table
if __name__ == '__main__':
app.run_server(port=8050, host='0.0.0.0')
I am getting the following error while running the code:
File "ipython-input-12-4bd6fe1b7399", line 28, in parse_contents content_type, content_string = contents.split(',') AttributeError: 'NoneType' object has no attribute 'split'
Upvotes: 0
Views: 300
Reputation: 6606
The callback is likely running on initialization with empty values. You can prevent this by adding something like this at the top of your callback:
if contents is None:
raise dash.exceptions.PreventUpdate
Upvotes: 1