问题描述
我是python和plotly-dash的新手。 我正在尝试使用“隐藏Div”来存储仪表板教程5中建议的数据框。 但是我无法处理上传的文件。
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')])
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')
文件“ ipython-input-12-4bd6fe1b7399”,第28行,位于parse_contents中 content_type,content_string = contents.split(',') AttributeError:'nonetype'对象没有属性'split'
解决方法
该回调可能在具有空值的初始化上运行。您可以通过在回调的顶部添加如下内容来防止这种情况:
if contents is None:
raise dash.exceptions.PreventUpdate