在 Flask 应用程序中运行 Dash 应用程序 [英] Running a Dash app within a Flask app

查看:50
本文介绍了在 Flask 应用程序中运行 Dash 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的 Flask 应用程序,我想有一个通往另一个应用程序的路径.更具体地说,第二个应用程序是 Plotly Dash 应用程序.如何在我现有的 Flask 应用中运行我的 Dash 应用?

@app.route('/plotly_dashboard')def render_dashboard():# 转到破折号应用程序

我还尝试向 Dash 实例添加路由,因为它是 Flask 应用程序,但出现错误:

AttributeError: 'Dash' 对象没有属性 'route'

解决方案

来自文档:><块引用>

底层 Flask 应用程序可在 app.server 处获得.

导入破折号app = dash.Dash(__name__)服务器 = app.server

您也可以将自己的 Flask 应用程序实例传递给 Dash:

导入烧瓶server = flask.Flask(__name__)app = dash.Dash(__name__, server=server)

现在你有了 Flask 实例,你可以添加任何你需要的路由和其他功能.

@server.route('/hello')定义你好():返回你好,世界!"


对于更一般的问题我如何才能为两个相邻的 Flask 实例提供服务",假设您最终没有像上面的 Dash 答案那样使用一个实例,您可以使用 DispatcherMiddleware 以挂载两个应用程序.

dash_app = Dash(__name__)flask_app = Flask(__name__)application = DispatcherMiddleware(flask_app, {'/dash': dash_app.server})

I have an existing Flask app, and I want to have a route to another app. More concretely, the second app is a Plotly Dash app. How can I run my Dash app within my existing Flask app?

@app.route('/plotly_dashboard') 
def render_dashboard():
    # go to dash app

I also tried adding a route to the Dash instance, since it's a Flask app, but I get the error:

AttributeError: 'Dash' object has no attribute 'route'

解决方案

From the docs:

The underlying Flask app is available at app.server.

import dash
app = dash.Dash(__name__)
server = app.server

You can also pass your own Flask app instance into Dash:

import flask
server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)

Now that you have the Flask instance, you can add whatever routes and other functionality you need.

@server.route('/hello')
def hello():
    return 'Hello, World!'


To the more general question "how can I serve two Flask instances next to each other", assuming you don't end up using one instance as in the above Dash answer, you would use DispatcherMiddleware to mount both applications.

dash_app = Dash(__name__)
flask_app = Flask(__name__)

application = DispatcherMiddleware(flask_app, {'/dash': dash_app.server})

这篇关于在 Flask 应用程序中运行 Dash 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆