【问题标题】:Python Dash: Update Layout from Outside of Callback-FunctionPython Dash:从回调函数外部更新布局
【发布时间】:2020-07-09 10:34:48
【问题描述】:

我的目标是在本地网络中的笔记本电脑上运行 Dash 应用程序,并从位于同一网络中的微控制器触发 HTTP 请求。这些请求应被 Dash 应用程序捕获,并应更新应用程序的布局。所以我的最终目标是为 Dash App 实现某种形式的远程控制。

当使用 Flask-server 并将其传递给 Dash-object 时,捕获 HTTP 请求是没有问题的:

import flask
import dash

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

...

@server.route('/start_switch', methods=['GET'])
def start_switch():
    print('server.route ran!')
    
    # What do i run here to update layout-elements?

    return Response('', 200)

...

但由于主要的交互性来自破折号回调,我不知道如何更新布局:

@app.callback(Output('show-status', 'children'),
              [Input('app2-status', 'children')])
def watch_kalibrierung(app2_status):
    """
    As soon as app2-status changes the function echoes
    its contents to the in div 'show-status'
    """
    return app2_status

因为现在,我不是在听 UI 元素的变化,而是在听 HTTP 请求。

我已经尝试过编写一个回调函数并从@server.route 函数中调用它,但是没有成功。

我怎样才能达到我想要的目标?

【问题讨论】:

    标签: python user-interface flask request plotly-dash


    【解决方案1】:

    您可以使用dcc.Interval 组件让前端例如每秒轮询一次更改。那么,

    类似

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output
    
    
    # Insert this component into your layout
    # Every 1000 milliseconds, the n_interval is increased, which 
    # can be tied to a callback
    interval = dcc.Interval(
        id='interval-component',
        interval=1000, # in milliseconds
        n_intervals=0
    )
    
    # Tie a callback to the interval
    @app.callback(Output('some-output-component', 'children'),
                  [Input('interval-component', 'n_intervals')])
    def update_metrics(n):
        some_stuff = check_http_requests() # your custom function
        component = html.Div(some_stuff) # create new children for some-output-component
        return component
    
    

    将数据从 HTTP 请求传递到 check_http_requests() 的一种简单方法是使用队列 (queue.Queue),您可以将 HTTP 请求放入其中。现在,这应该如何实现取决于您的需求。如果您需要能够同时为多个用户提供服务,您必须制定一个逻辑,以便每个用户都有自己的队列,应该检查这些队列。

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2016-12-06
      • 2018-06-23
      • 2020-06-08
      • 2020-09-22
      • 1970-01-01
      • 2020-03-18
      • 2021-10-08
      • 2019-04-30
      相关资源
      最近更新 更多