【问题标题】:Render DASH components via websocket通过 websocket 渲染 DASH 组件
【发布时间】:2020-02-25 10:27:59
【问题描述】:

是否可以在前端渲染序列化的 Dash 组件?

这是一个小型自容器应用程序,它将按钮单击链接到回调。 回调在内部通过套接字发出 5 条消息,这些消息从前端接收,并将消息的内容记录到控制台。

我想以某种方式利用DashRenderer 将序列化的 dash_html_components 呈现为正确的 HTML(并将它们插入到 HTML DOM 树中),而不是简单地将消息的内容记录到控制台。

import dash_html_components as html
from dash import Dash
from flask import Flask
from dash.dependencies import Input
from dash.dependencies import Output
from dash.exceptions import PreventUpdate
from flask_socketio import SocketIO

# add socketio script to javascript
external_scripts = [
    {
        'src': 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js',
        'integrity': 'sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=',
        'crossorigin': 'anonymous'
    }
]

server = Flask(__name__)
socketio = SocketIO(server)

app = Dash(__name__, server=server, external_scripts=external_scripts, serve_locally=True)

app.index_string = '''
<!DOCTYPE html>
<html>
    <head>
        {%metas%}
        <title>{%title%}</title>
        {%favicon%}
        {%css%}
    </head>
    <body>
        {%app_entry%}
        <footer>
            {%config%}
            {%scripts%}
            <script>
                var socket = io();
                socket.on("component-channel", function (component, cb) {
                   console.log("Component: ")
                   console.log(component)
                });
            </script>
            {%renderer%}
        </footer>
    </body>
</html>
'''

app.layout = html.Div(
    id="outer-div", children=[
        html.Button("Send event", id="button"),
        html.Div(id="output-div")
    ]
)


@app.callback(
    Output("output-div", "children"),
    [Input("button", "n_clicks")]
)
def on_click(n_clicks):
    if n_clicks is None:
        raise PreventUpdate()

    import time
    for i in range(5):
        component = html.P("Loop {}".format(i))
        serialised_component = component.to_plotly_json()
        socketio.emit("component-channel", serialised_component)
        time.sleep(2)

    return html.P("Terminated")


if __name__ == '__main__':

    app.run_server()

如何将 websocket 中接收到的数据渲染成正确的 HTML?

下面的 gif 显示了应用程序的当前行为,即通过 websocket 从服务器发送到前端的数据是通过控制台接收和记录的。

【问题讨论】:

    标签: javascript plotly plotly-dash


    【解决方案1】:

    看看this 我认为你应该使用

    React.createElement( type, [props], [...children] )

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 2019-12-30
      • 2013-08-25
      • 2017-06-01
      • 2018-03-03
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多