将带有路由的 Dash 应用程序集成到适当的 运行 Flask 环境中

Integrate a Dash app with a route into a proper running Flask environment

我在将适当的 运行 Dash 应用程序集成到 Flask 网站中遇到了一些困难。要么我在理解它的工作原理时遇到问题,要么这只是一个小问题。
欢迎每个提示。

@blueprint.route('/dash-test')
@login_required
def dash_test():
    """Integrate the Dash App into the page"""
    server = flask.Flask(__name__)
    return render_template('dashapp-test.html',
                           my_dashapp=my_dash_app(),
                           server=server
                           )
def my_dash_app():

    app = dash.Dash(
        __name__,
        external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css'],
    )

    app.layout = html.Div(id='example-div-element')
    return app

但预期是:显示 Dash App。

文档中的

This page 可能对您有用。它直接处理 Flask 应用程序中的 运行 Dash。这是他们提供的迷你示例:

import flask
import dash
import dash_html_components as html

server = flask.Flask(__name__)

@server.route('/')
def index():
    return 'Hello Flask app'

app = dash.Dash(
    __name__,
    server=server,
    routes_pathname_prefix='/dash/'
)

app.layout = html.Div("My Dash app")

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

需要记住的一点:当您生成 dashapp 时,您是在向现有的 flask 应用程序(也称为“服务器”)添加组件。一个合适的解决方案是构建你的 flask 应用程序 --> 然后用特定的路由构建你的 dash 应用程序 --> 然后在你的 flask 应用程序中构建一个到你的 dashapp 的路由:

# Create a function which creates your dashapp
import dash
def create_dashapp(server):
    app = dash.Dash(
        server=server,
        url_base_pathname='/dashapp/'
    )
    app.config['suppress_callback_exceptions'] = True
    app.title='Dash App'

    # Set the layout
    app.layout = layout = html.Div('Hello Dash app')

    # Register callbacks here if you want...
    
    return app


# Create your app (or server, same thing really)
server = flask.Flask(__name__)

# Initialize by passing through your function
create_dashapp(server)

# Define index route
@server.route('/')
def index():
    return 'Hello Flask app'


# Define dashapp route
@server.route('/dashapp/')
@login_required
def redirect_to_dashapp():
    return redirect('/dashapp/')


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