You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dash应用在http://127.0.0.1:8050/无法正常运行求助

Dash应用上传CSV后无内容显示问题排查

你的代码存在几个关键逻辑错误,导致上传文件后浏览器无反应,具体问题和修正方案如下:

核心问题分析

  • 异常处理逻辑倒置:你把「文件读取成功后的地图渲染」放到了except块里,而正常读取文件的try块没有任何返回值。这意味着只有文件读取失败时才会尝试返回内容,但此时df还未定义,会触发新错误;而文件读取成功时反而没有输出,浏览器自然显示空白。
  • 变量作用域错误:except块中引用的df仅在try块内定义,若读取失败,df不存在,会抛出NameError。
  • 未处理非CSV/XLS文件:没有对上传的非目标文件类型做提示处理。

修正后的完整代码

import dash
from dash import dcc, html, dash_table
import plotly.graph_objects as go
import pandas as pd
import base64
import datetime
import io
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.layout = 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'
        },
        multiple=True
    ),
    html.Div(id='output-data-upload'),
])

def parse_contents(contents, filename, date):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    
    try:
        if 'csv' in filename:
            df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            df = pd.read_excel(io.BytesIO(decoded))
        else:
            return html.Div([f"不支持的文件类型:{filename}"])
        
        # 读取成功后渲染地图
        fig = go.Figure(
            data=go.Scattergeo(
                lon=df['Lon_84'],
                lat=df['Lat_84'],
                text=df['text'],
                mode='markers',
                marker_color=df['Temp_C_ML']
            )
        )
        fig.update_layout(geo_scope='world')  # 可根据需求调整地图范围
        return html.Div([
            html.H5(filename),
            html.H6(datetime.datetime.fromtimestamp(date)),
            dash_table.DataTable(
                data=df.to_dict('records'),
                columns=[{'name': i, 'id': i} for i in df.columns],
                page_size=10
            ),
            dcc.Graph(figure=fig)
        ])
    
    except Exception as e:
        print(f"文件处理错误:{e}")
        return html.Div([
            f"文件解析失败:{str(e)}"
        ])

@app.callback(
    Output('output-data-upload', 'children'),
    Input('upload-data', 'contents'),
    State('upload-data', 'filename'),
    State('upload-data', 'last_modified')
)
def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)
        ]
        return children
    return html.Div(["请上传CSV或Excel文件"])

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

关键修改说明

  1. 调整异常处理逻辑:将地图渲染代码移到try块内,确保文件读取成功时返回地图和数据表格;except块仅处理错误情况,返回明确的错误提示。
  2. 增加文件类型校验:对非CSV/XLS文件返回不支持提示。
  3. 补充默认返回内容:未上传文件时显示提示文本,避免页面完全空白。
  4. 完善地图布局:添加update_layout设置地图范围,确保标记点正常显示。
  5. 添加数据表格预览:上传成功后显示文件内容预览,方便验证数据是否正确。

内容的提问来源于stack exchange,提问作者Konstantinos Sideris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:10:37