Plotly Dash:调试为 false 时使用 SMTP 日志记录处理程序

Plotly Dash: Use SMTP logging handler when debug is false

在 Plotly Dash 中,我正在尝试

  1. 确定我是否运行处于调试模式,并且
  2. 将日志记录处理程序更改为 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"]),但两者总是 return 错误。所以我无法确定应用程序是否真的处于调试模式。

这是我的控制台输出:

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)