如果创建了dash应用并从flask调用了dash应用,则dash回调不起作用

时间:2018-07-30 00:16:30

标签: flask plotly-dash

Dash应用程序创建并通过烧瓶服务器调用时失败。破折号的“回调”不起作用,并发出Post Request400。非常感谢您的帮助。

下面是重现该问题的示例代码。我使用最新的Dash 0.22.0,Dash HTML组件0.11.0和Dash Core组件0.24.1和Flask 1.0.2:

# file 'simple_flask.py'

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect


# Initialise flask App 
app = Flask(__name__, instance_relative_config=True)
#app.config.from_object('config.Config')

db = SQLAlchemy()         # SQLAlchemy
csrf_protect = CSRFProtect()

def set_app(app):

    # Setup WTForms CSRFProtect
    app.secret_key = 'My super secret key'
    csrf_protect.init_app(app)

    # Setup Flask-SQLAlchemy
    db.init_app(app) 

    # run in app context
    with app.test_request_context():
        db.create_all()

        from simple_dash import create_dash
        create_dash(app)


if __name__ == '__main__':
    set_app(app)
    app.run(host='127.0.0.1', port=5002, debug=True) 


## file 'simple_dash.py'

import dash
import dash_html_components as html
import dash_core_components as dcc

def create_dash(app):
    dash_app = dash.Dash(__name__, server=app, 
                        #static_folder='/static',
                        #url_base_pathname='/app/oga/', 
                        # csrf_protect=False
                        )
    dash_app.layout = html.Div([
        dcc.Dropdown(
            id='my-dropdown',
            options=[
                {'label': 'New York City', 'value': 'NYC'},
                {'label': 'Montreal', 'value': 'MTL'},
                {'label': 'San Francisco', 'value': 'SF'}
            ],
            value='NYC'
        ),
        html.Div(id='output-container')
    ])


    @dash_app.callback(
        dash.dependencies.Output('output-container', 'children'),
        [dash.dependencies.Input('my-dropdown', 'value')])
    def update_output(value):
        return 'You have selected "{}"'.format(value)

加载页面以及下拉菜单中的任何后续更改之后,缺少的参考是:“ POST / _dash-update-component HTTP / 1.1” 400。

1 个答案:

答案 0 :(得分:1)

在来自破折号github的@ T4rk1n的指示下,这是CSRFProtect烧瓶扩展名和Dash之间的冲突。下面显示了如何从CSRFProtect中排除Dash:

csrf_protect = CSRFProtect() csrf_protect._exempt_views.add('dash.dash.dispatch')