Build a realtime Dash App with websockets

Jacky Shi
3 min readDec 27, 2020

--

Dash is a Python framework for building analytical web applications, based on ReactJS. Currently, the official live update example is using an interval component to pull the data from server side, so it is pull mode.

In this article, I will try to create a push mode component which based on the websocket. Regarding how to crate a dash component, you can refer to Build A Custom Dash Component.

Step 1: Generate a dash component application based on template dash-component-boilerplate and install dependencies in README.md under your project folder

$ pip install cookiecutter
$ pip install virtualenv
$ cookiecutter https://github.com/plotly/dash-component-boilerplate.git
$ npm install
$ virtualenv venv
$ venv\Scripts\activate
$ pip install -r requirements.txt
$ pip install -r tests/requirements.txt

Step 2: Install websocket dependencies

$ npm i -save websocket
$ pip install websockets

Step 3: Create Websocket Dash Component

There are two parameters for this Dash Components. ‘url’ is to define the link that the websocket will connect, and ‘msg’ is the messages that returns from websocket server.

Remeber to put ‘msg’ in the component’s props and call ‘setProps’ when its value changes, hence it will be able to trigger the update of other dash component which depends on it.

Step 4: Create a websocket server

Now, we need to create an websocket server to continuously publish messages to our dash client. Here I am using package websockets that we have installed in Step2. The CLIENTS is a global variable store that stores the connections for all websocket clients.

Step 5: Create a test APP

Import ‘dash_websocket’ that we have created in Step 3. Set the DashWebsocket’s url to the path we defined in Step 4 and put the component into a hidden html div.

I am using dash_bootstrap_components example to display the result. Here I put the dummy stocks (‘ABC’, ‘DEF’, ‘GHI’, ‘JKL’) into different bookstrap Card.

For the callback function, I use DashWebsocket’s msg as input and the Cardbody of the dummy stocks as output.

Finally, you will see the screen like below. The dummy stocks are ticking!

We have created a realtime Dash App with websockets successfully!

If you open Callbacks’ hierarchy, you can see the websocket client distributes messages to each display Card.

I hope this article is helpful to you. If I missed anything, please kindly let me know! Thanks for reading!

--

--

Responses (1)