【发布时间】:2026-01-16 22:00:01
【问题描述】:
我正在尝试使用 Plotly Dash 对我的 Flask 应用程序执行一些操作。
基本上我想:
- 将 xls 文件上传到我的仪表板应用程序中
- 在预加载的 xls 上添加一些转换/计算
- 显示结果(作为数据表)
这是我的可重现代码。 加载 xls 文件后,我无法将结果显示为 Datatable。
谢谢
import io
import datetime
import base64
import pandas as pd
import dash_table as dt
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from flask import Flask
FA = "https://use.fontawesome.com/releases/v5.15.1/css/all.css"
server = Flask(__name__)
app = dash.Dash(
name=__name__,
server=server,
external_stylesheets=[dbc.themes.BOOTSTRAP, FA],
suppress_callback_exceptions=True
)
# file upload function
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
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))
elif 'xlsx' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return None
return df
# callback table creation
@app.callback(Output('table', 'data'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def update_output(contents, filename):
if contents is not None:
df = parse_contents(contents, filename)
# add some operations/calculations and show results
if df is not None:
return df.to_dict('records')
else:
return [{}]
else:
return [{}]
app.layout = html.Div([
html.H5("Upload Files"),
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
multiple=False),
html.Br(),
html.H5("Updated Table"),
html.Div(dt.DataTable(data=[], id='table'))
])
if __name__ == "__main__":
app.run_server(port=8888)
【问题讨论】:
标签: python pandas flask plotly-dash