【问题标题】:How to accept push notifications in a plotly/dash app?如何在 plotly/dash 应用程序中接受推送通知?
【发布时间】:2021-02-01 19:31:14
【问题描述】:

我有一个与服务器建立开放连接的客户端,该服务器接受来自服务器的推送通知。我想在 plotly/dash 页面中近乎实时地显示来自推送通知的数据。

我一直在考虑我在documentation page 中讨论的选项。

如果我在每个潜在的 plotly/dash 工作进程中运行多个推送通知客户端,那么我必须管理重复数据删除事件,这是可行的,但容易出错且代码古怪。

这个想法的解决方案似乎是只在一个进程上运行推送网络客户端,并将这些通知推送到dcc.Store 对象中。我假设我会通过在推送客户端异步回调中填充一个队列来做到这一点,并在 dcc.Interval 计时器上收集该队列中的任何新数据并将其放置在 dcc.Store 对象中。然后在 dcc.Store 对象上触发所有其他回调,可能在单独的 python 进程中。

从文档中我看不出我将如何保证与推送网络客户端交互到主进程的回调并确保它不会在任何工作进程上运行。这可能吗? dcc.Interval documentation 没有提及这个细节。

有没有办法将dcc.Interval 强制到一个进程上,或者这是在 Dash 下具有多个工作进程的正常操作?还是有其他推荐的方法来处理来自推送通知网络客户端的数据?

【问题讨论】:

    标签: python-3.x gunicorn plotly-dash


    【解决方案1】:

    Interval 组件定期拉取更新的替代方法是使用Websocket component 来启用推送通知。只需将组件添加到布局并添加一个客户端回调,该回调会根据收到的message 执行适当的更新,

    app.clientside_callback("function(msg){return \"Response from websocket: \" + msg.data;}",
                            Output("msg", "children"), [Input("ws", "message")])
    

    这是一个使用SocketPool 设置发送消息端点的完整示例,

    import dash_html_components as html
    from dash import Dash
    from dash.dependencies import Input, Output
    from dash_extensions.websockets import SocketPool, run_server
    from dash_extensions import WebSocket
    
    # Create example app.
    app = Dash(prevent_initial_callbacks=True)
    socket_pool = SocketPool(app)
    app.layout = html.Div([html.Div(id="msg"), WebSocket(id="ws")])
    # Update div using websocket.
    app.clientside_callback("function(msg){return \"Response from websocket: \" + msg.data;}",
                            Output("msg", "children"), [Input("ws", "message")])
    
    
    # End point to send message to current session.
    @app.server.route("/send/<message>")
    def send_message(message):
        socket_pool.send(message)
        return f"Message [{message}] sent."
    
    
    # End point to broadcast message to ALL sessions.
    @app.server.route("/broadcast/<message>")
    def broadcast_message(message):
        socket_pool.broadcast(message)
        return f"Message [{message}] broadcast."
    
    
    if __name__ == '__main__':
        run_server(app)
    

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2015-12-06
      • 2012-12-26
      • 1970-01-01
      • 2020-07-12
      相关资源
      最近更新 更多