我在 Plotly Dash 中创建了一个相当复杂的可视化工具,因此我不会共享整个代码,尽管我想做的是使用 try/ except 块返回错误消息。
except Exception as e:
print(e)
return html.Div([
html.B('THERE WAS AN ERROR PROCESSING THIS FILE - PLEASE REVIEW FORMATTING.')
])
从技术上讲,这是可行的,但我找不到将消息作为第一个
html.Div
返回的方法,因此位于页面顶部。目前它返回到底部。以前有人尝试过解决这个问题吗?
很难用很少的信息找出准确的答案,但假设你使用
@callback
函数,我认为这样的东西应该有效:
from dash import Dash, html, callback, Input, Output
app = Dash(__name__)
app.layout = html.Div([
html.Div(
id='error-div' # your error message will be displayed here, if there is one
),
html.Div(
id='your-usual-content' # if everythin works, your file gets displayed here or sth like that
)
])
@callback(
Output('error-div', 'children'),
Output('your-usual-content', 'children'),
Input('file-upload', 'contents')) # contents is just a guess here
def process_file(file):
try:
# do something with your file here
return None, 'Whatever you want to return here, if it worked.' # first return value is for the first Output (id='error-div'), second return value is for the second Output (id='your-usual-content')
except:
return html.B('THERE WAS AN ERROR PROCESSING THIS FILE - PLEASE REVIEW FORMATTING.'), ''
if __name__ == '__main__':
app.run_server()
基本上,您可以在您正在使用的
@callback
函数中进行错误处理(如果这样做)并返回例如html.Div
或您在 html.Div
中实施的某些 app.layout
的任何其他内容。如果您根本不想渲染 Div
- 例如因为没有错误 - 你只需返回 None
。