Dash content update from external websocket client

I try to update the data in the Dash from the external client sending websockets. I have tried the next code for minimal Dash application:

Dash application app.py

from dash import html, dcc, Dash, Input, Output, State
from dash_extensions import WebSocket
from dash_extensions.websockets import SocketPool, run_server

# Create example app.
app = Dash(prevent_initial_callbacks=True)
socket_pool = SocketPool(app)
app.layout = html.Div([html.Div(id="msg1"),
                       WebSocket(url="ws://localhost:8050", id="ws2"),
                       ])

@app.callback(Output("msg1", "children"),
              [Input("ws2", "message")],
              )
def update_div(msg):
    return f'Message: {msg}'


if __name__ == '__main__':
    pass
    run_server(app, port=8050)  # 5000 if the default port

And another program is client for websocket generation (emulate the uController in the future):
Websocket client client.py

import json
import websocket
from websocket import create_connection
from time import sleep

from icecream import ic

websocket.enableTrace(True)
ws = create_connection('ws://localhost:8050')

msg = {'data': '0.46641500410263426'}

msg = 0.2324
data = json.dumps(msg)
# ws.send(bytes(data, encoding="utf-8"))
ws.send(data)
sleep(1)
ws.send(data)
sleep(1)
ws.send(data)

sleep(2)
ws.close()

But the Dash app html.Div(id=“msg1”) content doesn’t updated.

Can somebody help me with this minimal setup?

For me the main question is:

How the client app have to generate websockets to be compatable with dash_extensions websockets?

Or may be alternative solutions are exist to update the dash app content from the external client sending data?

Thanks!

1 Like