How to display dash_table for a selected radio item

46 Views Asked by At

I am new python Dash programming, and i have taken reference from plotly.community. I am able display list of s3 buckets from my AWS account, and for a selected bucket I am showing list of all CSV files.

The next step is, for a selected CSV file, I need to display CSV contents as a dash table on the same page just below the radio buttons, with a scroll bar and pagination. Appreciate any help pls. I am stuck here, please help.

This is what i have tried thus far:

from dash import Dash, dcc, html, Input, Output, callback, dash_table
import boto3
import pandas as pd

# Retrieve the list of existing buckets
s3 = boto3.client('s3')
response = s3.list_buckets()
all_options = {}

# Output the bucket names
for bucket in response['Buckets']:
    # print(f'  {bucket["Name"]}')
    if bucket["Name"].startswith("ag-"):
        if len(all_options) < 5:
            # Get a list of all objects in the bucket
            objects = s3.list_objects_v2(Bucket=bucket['Name'])
            # Create a list to store the files in the bucket
            files = []

            # Iterate over the objects
            for obj in objects['Contents']:
                if obj['Key'].endswith('.csv'):
                    if len(files) < 5:
                        # Add the file name to the list
                        files.append(obj['Key'])
            # Add the bucket and files to the dictionary
            all_options[bucket['Name']] = files


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

app = Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.RadioItems(
        list(all_options.keys()),
        0,
        id='buckets-radio',
    ),

    html.Hr(),
    dcc.RadioItems(id='files-radio'),
    html.Hr(),
    html.Div(id='display-selected-values')
])


@callback(
    Output('files-radio', 'options'),
    Input('buckets-radio', 'value'))
def set_cities_options(selected_bucket):
    return [{'label': i, 'value': i} for i in all_options[selected_bucket]]


@callback(
    Output('files-radio', 'value'),
    Input('files-radio', 'options'))
def set_cities_value(available_options):
    return available_options[0]['value']

@callback(
    Output('display-selected-values', 'children'),
    Input('buckets-radio', 'value'),
    Input('files-radio', 'value'))
def set_display_children(selected_bucket, selected_file):
    # obj = s3.get_object(Bucket=selected_country, Key=selected_city)
    # df = pd.read_csv(obj['Body'])
    #
    # app.layout = html.Div([
    #     html.H4('Simple interactive table'),
    #     html.P(id='table_out'),
    #     dash_table.DataTable(
    #         id='table',
    #         columns=[{"name": i, "id": i}
    #                  for i in df.columns],
    #         data=df.to_dict('records'),
    #         style_cell=dict(textAlign='left'),
    #         style_header=dict(backgroundColor="paleturquoise"),
    #         style_data=dict(backgroundColor="lavender")
    #     ),
    # ])
    #
    # def update_graphs(active_cell):
    #     if active_cell:
    #         cell_data = df.iloc[active_cell['row']][active_cell['column_id']]
    #         return f"Data: \"{cell_data}\" from table cell: {active_cell}"
    #     return "Click the table"

    return f'{selected_file} is a file in {selected_bucket}'


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

app.run_server(debug=True)
1

There are 1 best solutions below

0
flipSTAR On

Your function set_display_children is not returning a div-children but a string, that is probably the biggest issue here.

Try changing these

from app.layout = html.Div([ to returnvaluename = html.Div([

and this from return f'{selected_file} is a file in {selected_bucket}' to return returnvaluename

I am also quite new to dash, so I am not sure if this is the only problem, as I do not know if it is possible to return a whole div-child (as you try in Output('display-selected-values', 'children')

If it does not work try returning just the datatable to the data entry of a dash_table.DataTable item in your layout