在Plotly Dash中,我正在尝试
- 确定我是否在调试模式下运行,以及
- 仅当应用程序未在调试模式下运行时,才将日志记录处理程序更改为SMTPHandler
我尝试了什么:
import dash
app = dash.Dash(__name__)
if app.server.debug is False:
print("Not in Debug mode")
# app.logger.addHandler(mail_handler)
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=True)
print(f"app.server.debug is {app.server.debug}") # This code only executes after the server is shut down
我尝试了app.server.debug
(和app.server.config["DEBUG"]
(,但两者总是返回False。因此,我无法确定该应用程序是否真的处于调试模式。
这是我的控制台输出:
Not in Debug mode Dash is running on http://127.0.0.1:8050/ * Serving Flask app 'example_code' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on Not in Debug mode
我认为这种混淆是因为没有设置FLASK_DEBUG
环境变量,但即使如此,它也会说* Debug mode: on
,那么如何在运行时识别它呢?
最后,我该在哪里添加调试模式检查并更改处理程序——调试是在app.run_server()
中设置的,但在调试之后立即添加任何代码都只在服务器关闭后执行。
也许这种方法对你有用?只需将回调设置为每次程序执行仅运行一次。(很抱歉使用全局变量,想不出更干净的方法(。
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import logging
app = dash.Dash(__name__)
app.layout = html.Div([dcc.Store(id='dummy_store')])
logger = logging.getLogger(__name__)
LOGGER_CONFIGURED = False
@app.callback(
Output('dummy_store', 'data'),
Input('dummy_store', 'data'),
)
def configure_logger(dummy_store):
global LOGGER_CONFIGURED
if LOGGER_CONFIGURED is False:
print(f'configured logger with debug mode set to {app.server.debug}')
# do something with the logger here
LOGGER_CONFIGURED = True
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=True)