我是Python Dash编程新手,我参考了plotly.community。我可以显示我的 AWS 账户中的 s3 存储桶列表,并且对于选定的存储桶,我将显示所有 CSV 文件的列表。
下一步是,对于选定的 CSV 文件,我需要在单选按钮下方的同一页面上将 CSV 内容显示为破折号表,并带有滚动条和分页。感谢任何帮助。我被困在这里,请帮忙。
这是我迄今为止尝试过的:
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)
你的函数
set_display_children
不是返回一个div-children而是一个字符串,这可能是这里最大的问题。
尝试改变这些
从
app.layout = html.Div([
到returnvaluename = html.Div([
还有这个 从
return f'{selected_file} is a file in {selected_bucket}'
到 return returnvaluename
我对 dash 也很陌生,所以我不确定这是否是唯一的问题,因为我不知道是否可以返回整个 div-child (正如您在
Output('display-selected-values', 'children')
中尝试的那样)
如果不起作用,请尝试仅将数据表返回到布局中
data
项目的dash_table.DataTable
条目