✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Unable to use Upload Component

I am using the Upload Component, when I use only one callback to update a Div it works but when I add another callback to update a Graph component it doesn’t work. Even the earlier working Div update stops working. Please help me out.

app.layout = html.Div([
	html.Div([
		    dcc.Upload(
        id='upload-data',
        children=html.Div([
            'Drag and Drop or ',
            html.A('Select Files')
        ]),
        style={
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        # Allow multiple files to be uploaded
        multiple=False
    ),
	]),
	html.H1(id='output'),
	html.Div([
		dcc.Graph(id='graph1')])
	])
def parse_contents(list_of_contents,filename):
	content_type, content_string = str(list_of_contents).split(',')
	decoded = base64.b64decode(content_string)
	try:
		if 'csv' in filename:
			df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
			print('File loaded Successfully')
			return df 
		elif 'xls' in filename:
			df = pd.read_excel(io.BytesIO(decoded))
			print('File Loaded Successfully')
			return df
	except Exception as e:
		print(e)
@app.callback(Output('output','children'),
              [Input('upload-data', 'contents'),
               Input('upload-data', 'filename'),
               Input('upload-data', 'last_modified')])
def update_data(list_of_contents, list_of_names, list_of_dates):
	if list_of_names is not None:
		print('Initiated')
		dataframe = parse_contents(list_of_contents,list_of_names)
		tweets_per_day = dataframe.groupby('created_at').count()
		return str(tweets_per_day)
if __name__ == '__main__':
	app.run_server()'

The above code works, whereas the below code fails to do anything,

app = dash.Dash() 

app.layout = html.Div([
	html.Div([
		    dcc.Upload(
        id='upload-data',
        children=html.Div([
            'Drag and Drop or ',
            html.A('Select Files')
        ]),
        style={
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        # Allow multiple files to be uploaded
        multiple=False
    ),
	]),
	html.H1(id='output'),
	html.Div([
		dcc.Graph(id='graph1')])
	])
def parse_contents(list_of_contents,filename):
	content_type, content_string = str(list_of_contents).split(',')
	decoded = base64.b64decode(content_string)
	try:
		if 'csv' in filename:
			df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
			print('File loaded Successfully')
			return df 
		elif 'xls' in filename:
			df = pd.read_excel(io.BytesIO(decoded))
			print('File Loaded Successfully')
			return df
	except Exception as e:
		print(e)
@app.callback(Output('output','children'),
              [Input('upload-data', 'contents'),
               Input('upload-data', 'filename'),
               Input('upload-data', 'last_modified')])
def update_data(list_of_contents, list_of_names, list_of_dates):
	if list_of_names is not None:
		print('Initiated')
		dataframe = parse_contents(list_of_contents,list_of_names)
		tweets_per_day = dataframe.groupby('created_at').count()
		return str(tweets_per_day)
@app.callback(Output('output2','children'),
              [Input('upload-data', 'contents'),
               Input('upload-data', 'filename'),
               Input('upload-data', 'last_modified')])
def update_data2(list_of_contents, list_of_names, list_of_dates):
	if list_of_names is not None:
		print('Initiated2')
		dataframe = parse_contents(list_of_contents,list_of_names)
		tweets_per_day = dataframe.groupby('created_at').count()
		return str(tweets_per_day)
@app.callback(Output('graph1','figure'),
              [Input('upload-data', 'contents'),
               Input('upload-data', 'filename'),
               Input('upload-data', 'last_modified')])
def update_graph(list_of_contents, list_of_names, list_of_dates):
	if list_of_names is not None:
		print('Initiated')
		dataframe = parse_contents(list_of_contents,list_of_names)
		tweets_per_day = dataframe.groupby('created_at').count()
		return {
			'data': [go.Scatter(
				x =tweets_per_day.index.values,
				y = tweets_per_day.tweet_id,
				mode='lines+markers',
				fill='tozeroy',
				text = 'Posts',
				hoverinfo='y+text',
				hoverlabel=dict(
					bgcolor='#000000'))
			],
			'layout': go.Layout(
				title='Tweets per day',
				xaxis={'title':'Date'},
				yaxis={'title':'Number of tweets'},
				hovermode='closest'
				)
			}

if __name__ == '__main__':
	app.run_server()

Please help me

2 Likes

I am having exactly the same issue and it looks like it has been there for quite a while - or simply me and @sharmaji don’t understand something. I can use Upload component as described in the manual but it fails silently when I try to output to Graph. @chriddyp Do you think you could have a look at this?

Below is a reproducible example. If you comment out update_figure, the code will work. Otherwise all events get unsubscribed.

Please help…

import numpy as np
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.scripts.config.serve_locally = True

app.layout = html.Div([
    dcc.Graph(
        id='myfig',
        style={'height': '90vh'}
    ),
    dcc.Upload(
        id='upload-data',
        children=html.Div([
            'Drag and Drop or ',
            html.A('Select Files')
        ]),
        style={
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        multiple=False
        # Allow multiple files to be uploaded
    ),
    html.Div(id='output-data-upload'),
])

def test_scatter() -> go.Figure:
    N = 100
    random_x = np.random.randn(N)
    random_y = np.random.randn(N)

    trace = go.Scatter(
        x=random_x,
        y=random_y,
        mode='markers'
    )

    fig = go.Figure(data=[trace])
    return fig

@app.callback(Output('myfig', 'figure'),
              [Input('upload-data', 'contents')],
              [State('upload-data', 'filename'),
               State('upload-data', 'last_modified')])
def update_figure(content, filename, date):
    if content is not None:
        return test_scatter()

@app.callback(Output('output-data-upload', 'children'),
              [Input('upload-data', 'contents')],
              [State('upload-data', 'filename'),
               State('upload-data', 'last_modified')])
def update_output(content, filename, date):
    if content is not None:
        return html.Div([
            dcc.Graph(
                id='example-graph',
                figure={
                    'data': test_scatter(),
                    'layout': {
                        'title': filename
                    }
                }
            )
        ])


if __name__ == '__main__':
    app.run_server(debug=True)

I face the same issue, it works fine when there is just one callback associated, but stops working when I add a graph div. Has this been resolved?

Was this resolved? I am using the dcc.Upload component and it fails silently when I attempt to upload csv or excel file.