Dash populate dcc.Dropdown with row from xlsx/csv loaded with upload field












1















I have in my dash app a fileinput which is bound to a callback that should populate a dropdown.



Doesnt work, I somehow it ignores the file upload, when I cange the callback output to some div, the callback is triggered.



But this does not help me as I want to read the data head as options for my dropdown.



I have seen an example were they used a table as buffer, but my amoutn of data is just too much to render in a table, so thats not an option for me.



dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
multiple=True),

dcc.Dropdown(
id="select_column",
options=[{}],
searchable=True),


Here the callback



@app.callback(Output('select_column', 'options'),
[Input('upload-data', 'contents')],
[State('upload-data', 'filename'),
State('upload-data', 'last_modified'),
State('separator', 'value')])
def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
if list_of_contents is not None:
#print('list_of_contents: '+str(list_of_contents))
print('size of contents: '+str(len(list_of_contents[0])))
print('list_of_names: '+str(list_of_names))
print('list_of_dates: '+str(list_of_dates))
print('seperator: '+separator)
options = [
parse_contents(c, n, d, s) for c, n, d, s in
zip(list_of_contents, list_of_names, list_of_dates, separator)]
print("options variable: "+str(options))
return options


full example:



import base64
import datetime
import io

from dash.dependencies import Input, Output, State

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt


import pandas as pd
from builtins import str


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

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

df = None
cols = None


app.layout = html.Div(children=[
html.H1(children='AK2Viz'),

html.Div(children='''
Large Data Visualizer
'''),

dcc.RadioItems(
id='separator',
options=[
{'label': 'Semicolon', 'value': ';'},
{'label': 'Comma or Excel', 'value': ','},
],
value=',',
labelStyle={'display': 'inline-block'}),

dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '50%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
multiple=True),

dcc.Dropdown(
id="select_column",
options=[{}
#({}) if ( df is None ) else
#( {'label': df.iloc[[0][i]], 'value': i} for i in df.iloc[[0]] )
],
searchable=True),

html.Div(id='output-container',
children="helper div"),
html.Div(id='col_helper', children='col_helper')
])


@app.callback(
dash.dependencies.Output('output-container', 'children'),
[dash.dependencies.Input('select_column', 'value')])
def update_output(value):
return 'You have selected "{}"'.format(value)

def parse_contents(contents, filename, date, separator):
content_type, content_string = contents.split(separator)

decoded = base64.b64decode(content_string)
print('decoded len: '+str(len(decoded)))
print('decoded raw: '+str(decoded[0:100]))
print('io.Bytes len: '+str(io.BytesIO(decoded).getbuffer().nbytes))
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded), sheet_name=1)
print('df.empty: '+str(df.empty))
print('row for drodown: '+str(df.iloc[[0]]))
print('len of row for drodown: '+str(len(df.iloc[[0]])))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return [{'label': i, 'value': i } for i in df.iloc[[0]]]



@app.callback(Output('select_column', 'options'),
[Input('upload-data', 'contents')],
[State('upload-data', 'filename'),
State('upload-data', 'last_modified'),
State('separator', 'value')])
def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
if list_of_contents is not None:
#print('list_of_contents: '+str(list_of_contents))
print('size of contents: '+str(len(list_of_contents[0])))
print('list_of_names: '+str(list_of_names))
print('list_of_dates: '+str(list_of_dates))
print('seperator: '+separator)
options = [
parse_contents(c, n, d, s) for c, n, d, s in
zip(list_of_contents, list_of_names, list_of_dates, separator)]
print("options variable: "+str(options))
return options

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









share|improve this question



























    1















    I have in my dash app a fileinput which is bound to a callback that should populate a dropdown.



    Doesnt work, I somehow it ignores the file upload, when I cange the callback output to some div, the callback is triggered.



    But this does not help me as I want to read the data head as options for my dropdown.



    I have seen an example were they used a table as buffer, but my amoutn of data is just too much to render in a table, so thats not an option for me.



    dcc.Upload(
    id='upload-data',
    children=html.Div([
    'Drag and Drop or ',
    html.A('Select Files')
    ]),
    multiple=True),

    dcc.Dropdown(
    id="select_column",
    options=[{}],
    searchable=True),


    Here the callback



    @app.callback(Output('select_column', 'options'),
    [Input('upload-data', 'contents')],
    [State('upload-data', 'filename'),
    State('upload-data', 'last_modified'),
    State('separator', 'value')])
    def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
    if list_of_contents is not None:
    #print('list_of_contents: '+str(list_of_contents))
    print('size of contents: '+str(len(list_of_contents[0])))
    print('list_of_names: '+str(list_of_names))
    print('list_of_dates: '+str(list_of_dates))
    print('seperator: '+separator)
    options = [
    parse_contents(c, n, d, s) for c, n, d, s in
    zip(list_of_contents, list_of_names, list_of_dates, separator)]
    print("options variable: "+str(options))
    return options


    full example:



    import base64
    import datetime
    import io

    from dash.dependencies import Input, Output, State

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    import dash_table_experiments as dt


    import pandas as pd
    from builtins import str


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

    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

    df = None
    cols = None


    app.layout = html.Div(children=[
    html.H1(children='AK2Viz'),

    html.Div(children='''
    Large Data Visualizer
    '''),

    dcc.RadioItems(
    id='separator',
    options=[
    {'label': 'Semicolon', 'value': ';'},
    {'label': 'Comma or Excel', 'value': ','},
    ],
    value=',',
    labelStyle={'display': 'inline-block'}),

    dcc.Upload(
    id='upload-data',
    children=html.Div([
    'Drag and Drop or ',
    html.A('Select Files')
    ]),
    style={
    'width': '50%',
    'height': '60px',
    'lineHeight': '60px',
    'borderWidth': '1px',
    'borderStyle': 'dashed',
    'borderRadius': '5px',
    'textAlign': 'center',
    'margin': '10px'
    },
    multiple=True),

    dcc.Dropdown(
    id="select_column",
    options=[{}
    #({}) if ( df is None ) else
    #( {'label': df.iloc[[0][i]], 'value': i} for i in df.iloc[[0]] )
    ],
    searchable=True),

    html.Div(id='output-container',
    children="helper div"),
    html.Div(id='col_helper', children='col_helper')
    ])


    @app.callback(
    dash.dependencies.Output('output-container', 'children'),
    [dash.dependencies.Input('select_column', 'value')])
    def update_output(value):
    return 'You have selected "{}"'.format(value)

    def parse_contents(contents, filename, date, separator):
    content_type, content_string = contents.split(separator)

    decoded = base64.b64decode(content_string)
    print('decoded len: '+str(len(decoded)))
    print('decoded raw: '+str(decoded[0:100]))
    print('io.Bytes len: '+str(io.BytesIO(decoded).getbuffer().nbytes))
    try:
    if 'csv' in filename:
    # Assume that the user uploaded a CSV file
    df = pd.read_csv(
    io.StringIO(decoded.decode('utf-8')))
    elif 'xls' in filename:
    # Assume that the user uploaded an excel file
    df = pd.read_excel(io.BytesIO(decoded), sheet_name=1)
    print('df.empty: '+str(df.empty))
    print('row for drodown: '+str(df.iloc[[0]]))
    print('len of row for drodown: '+str(len(df.iloc[[0]])))
    except Exception as e:
    print(e)
    return html.Div([
    'There was an error processing this file.'
    ])
    return [{'label': i, 'value': i } for i in df.iloc[[0]]]



    @app.callback(Output('select_column', 'options'),
    [Input('upload-data', 'contents')],
    [State('upload-data', 'filename'),
    State('upload-data', 'last_modified'),
    State('separator', 'value')])
    def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
    if list_of_contents is not None:
    #print('list_of_contents: '+str(list_of_contents))
    print('size of contents: '+str(len(list_of_contents[0])))
    print('list_of_names: '+str(list_of_names))
    print('list_of_dates: '+str(list_of_dates))
    print('seperator: '+separator)
    options = [
    parse_contents(c, n, d, s) for c, n, d, s in
    zip(list_of_contents, list_of_names, list_of_dates, separator)]
    print("options variable: "+str(options))
    return options

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









    share|improve this question

























      1












      1








      1








      I have in my dash app a fileinput which is bound to a callback that should populate a dropdown.



      Doesnt work, I somehow it ignores the file upload, when I cange the callback output to some div, the callback is triggered.



      But this does not help me as I want to read the data head as options for my dropdown.



      I have seen an example were they used a table as buffer, but my amoutn of data is just too much to render in a table, so thats not an option for me.



      dcc.Upload(
      id='upload-data',
      children=html.Div([
      'Drag and Drop or ',
      html.A('Select Files')
      ]),
      multiple=True),

      dcc.Dropdown(
      id="select_column",
      options=[{}],
      searchable=True),


      Here the callback



      @app.callback(Output('select_column', 'options'),
      [Input('upload-data', 'contents')],
      [State('upload-data', 'filename'),
      State('upload-data', 'last_modified'),
      State('separator', 'value')])
      def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
      if list_of_contents is not None:
      #print('list_of_contents: '+str(list_of_contents))
      print('size of contents: '+str(len(list_of_contents[0])))
      print('list_of_names: '+str(list_of_names))
      print('list_of_dates: '+str(list_of_dates))
      print('seperator: '+separator)
      options = [
      parse_contents(c, n, d, s) for c, n, d, s in
      zip(list_of_contents, list_of_names, list_of_dates, separator)]
      print("options variable: "+str(options))
      return options


      full example:



      import base64
      import datetime
      import io

      from dash.dependencies import Input, Output, State

      import dash
      import dash_core_components as dcc
      import dash_html_components as html
      import dash_table_experiments as dt


      import pandas as pd
      from builtins import str


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

      app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

      df = None
      cols = None


      app.layout = html.Div(children=[
      html.H1(children='AK2Viz'),

      html.Div(children='''
      Large Data Visualizer
      '''),

      dcc.RadioItems(
      id='separator',
      options=[
      {'label': 'Semicolon', 'value': ';'},
      {'label': 'Comma or Excel', 'value': ','},
      ],
      value=',',
      labelStyle={'display': 'inline-block'}),

      dcc.Upload(
      id='upload-data',
      children=html.Div([
      'Drag and Drop or ',
      html.A('Select Files')
      ]),
      style={
      'width': '50%',
      'height': '60px',
      'lineHeight': '60px',
      'borderWidth': '1px',
      'borderStyle': 'dashed',
      'borderRadius': '5px',
      'textAlign': 'center',
      'margin': '10px'
      },
      multiple=True),

      dcc.Dropdown(
      id="select_column",
      options=[{}
      #({}) if ( df is None ) else
      #( {'label': df.iloc[[0][i]], 'value': i} for i in df.iloc[[0]] )
      ],
      searchable=True),

      html.Div(id='output-container',
      children="helper div"),
      html.Div(id='col_helper', children='col_helper')
      ])


      @app.callback(
      dash.dependencies.Output('output-container', 'children'),
      [dash.dependencies.Input('select_column', 'value')])
      def update_output(value):
      return 'You have selected "{}"'.format(value)

      def parse_contents(contents, filename, date, separator):
      content_type, content_string = contents.split(separator)

      decoded = base64.b64decode(content_string)
      print('decoded len: '+str(len(decoded)))
      print('decoded raw: '+str(decoded[0:100]))
      print('io.Bytes len: '+str(io.BytesIO(decoded).getbuffer().nbytes))
      try:
      if 'csv' in filename:
      # Assume that the user uploaded a CSV file
      df = pd.read_csv(
      io.StringIO(decoded.decode('utf-8')))
      elif 'xls' in filename:
      # Assume that the user uploaded an excel file
      df = pd.read_excel(io.BytesIO(decoded), sheet_name=1)
      print('df.empty: '+str(df.empty))
      print('row for drodown: '+str(df.iloc[[0]]))
      print('len of row for drodown: '+str(len(df.iloc[[0]])))
      except Exception as e:
      print(e)
      return html.Div([
      'There was an error processing this file.'
      ])
      return [{'label': i, 'value': i } for i in df.iloc[[0]]]



      @app.callback(Output('select_column', 'options'),
      [Input('upload-data', 'contents')],
      [State('upload-data', 'filename'),
      State('upload-data', 'last_modified'),
      State('separator', 'value')])
      def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
      if list_of_contents is not None:
      #print('list_of_contents: '+str(list_of_contents))
      print('size of contents: '+str(len(list_of_contents[0])))
      print('list_of_names: '+str(list_of_names))
      print('list_of_dates: '+str(list_of_dates))
      print('seperator: '+separator)
      options = [
      parse_contents(c, n, d, s) for c, n, d, s in
      zip(list_of_contents, list_of_names, list_of_dates, separator)]
      print("options variable: "+str(options))
      return options

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









      share|improve this question














      I have in my dash app a fileinput which is bound to a callback that should populate a dropdown.



      Doesnt work, I somehow it ignores the file upload, when I cange the callback output to some div, the callback is triggered.



      But this does not help me as I want to read the data head as options for my dropdown.



      I have seen an example were they used a table as buffer, but my amoutn of data is just too much to render in a table, so thats not an option for me.



      dcc.Upload(
      id='upload-data',
      children=html.Div([
      'Drag and Drop or ',
      html.A('Select Files')
      ]),
      multiple=True),

      dcc.Dropdown(
      id="select_column",
      options=[{}],
      searchable=True),


      Here the callback



      @app.callback(Output('select_column', 'options'),
      [Input('upload-data', 'contents')],
      [State('upload-data', 'filename'),
      State('upload-data', 'last_modified'),
      State('separator', 'value')])
      def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
      if list_of_contents is not None:
      #print('list_of_contents: '+str(list_of_contents))
      print('size of contents: '+str(len(list_of_contents[0])))
      print('list_of_names: '+str(list_of_names))
      print('list_of_dates: '+str(list_of_dates))
      print('seperator: '+separator)
      options = [
      parse_contents(c, n, d, s) for c, n, d, s in
      zip(list_of_contents, list_of_names, list_of_dates, separator)]
      print("options variable: "+str(options))
      return options


      full example:



      import base64
      import datetime
      import io

      from dash.dependencies import Input, Output, State

      import dash
      import dash_core_components as dcc
      import dash_html_components as html
      import dash_table_experiments as dt


      import pandas as pd
      from builtins import str


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

      app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

      df = None
      cols = None


      app.layout = html.Div(children=[
      html.H1(children='AK2Viz'),

      html.Div(children='''
      Large Data Visualizer
      '''),

      dcc.RadioItems(
      id='separator',
      options=[
      {'label': 'Semicolon', 'value': ';'},
      {'label': 'Comma or Excel', 'value': ','},
      ],
      value=',',
      labelStyle={'display': 'inline-block'}),

      dcc.Upload(
      id='upload-data',
      children=html.Div([
      'Drag and Drop or ',
      html.A('Select Files')
      ]),
      style={
      'width': '50%',
      'height': '60px',
      'lineHeight': '60px',
      'borderWidth': '1px',
      'borderStyle': 'dashed',
      'borderRadius': '5px',
      'textAlign': 'center',
      'margin': '10px'
      },
      multiple=True),

      dcc.Dropdown(
      id="select_column",
      options=[{}
      #({}) if ( df is None ) else
      #( {'label': df.iloc[[0][i]], 'value': i} for i in df.iloc[[0]] )
      ],
      searchable=True),

      html.Div(id='output-container',
      children="helper div"),
      html.Div(id='col_helper', children='col_helper')
      ])


      @app.callback(
      dash.dependencies.Output('output-container', 'children'),
      [dash.dependencies.Input('select_column', 'value')])
      def update_output(value):
      return 'You have selected "{}"'.format(value)

      def parse_contents(contents, filename, date, separator):
      content_type, content_string = contents.split(separator)

      decoded = base64.b64decode(content_string)
      print('decoded len: '+str(len(decoded)))
      print('decoded raw: '+str(decoded[0:100]))
      print('io.Bytes len: '+str(io.BytesIO(decoded).getbuffer().nbytes))
      try:
      if 'csv' in filename:
      # Assume that the user uploaded a CSV file
      df = pd.read_csv(
      io.StringIO(decoded.decode('utf-8')))
      elif 'xls' in filename:
      # Assume that the user uploaded an excel file
      df = pd.read_excel(io.BytesIO(decoded), sheet_name=1)
      print('df.empty: '+str(df.empty))
      print('row for drodown: '+str(df.iloc[[0]]))
      print('len of row for drodown: '+str(len(df.iloc[[0]])))
      except Exception as e:
      print(e)
      return html.Div([
      'There was an error processing this file.'
      ])
      return [{'label': i, 'value': i } for i in df.iloc[[0]]]



      @app.callback(Output('select_column', 'options'),
      [Input('upload-data', 'contents')],
      [State('upload-data', 'filename'),
      State('upload-data', 'last_modified'),
      State('separator', 'value')])
      def update_col_helper(list_of_contents, list_of_names, list_of_dates, separator):
      if list_of_contents is not None:
      #print('list_of_contents: '+str(list_of_contents))
      print('size of contents: '+str(len(list_of_contents[0])))
      print('list_of_names: '+str(list_of_names))
      print('list_of_dates: '+str(list_of_dates))
      print('seperator: '+separator)
      options = [
      parse_contents(c, n, d, s) for c, n, d, s in
      zip(list_of_contents, list_of_names, list_of_dates, separator)]
      print("options variable: "+str(options))
      return options

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






      python callback dash






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 14:57









      jteichertjteichert

      8613




      8613
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414781%2fdash-populate-dcc-dropdown-with-row-from-xlsx-csv-loaded-with-upload-field%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414781%2fdash-populate-dcc-dropdown-with-row-from-xlsx-csv-loaded-with-upload-field%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          Npm cannot find a required file even through it is in the searched directory

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith