Currently, I am working on a page that needs to display live-updating data to the client. The rest of the website is constructed using Django framework, so my approach involves utilizing Channels for this purpose.
The data that needs to be showcased is stored in both a JSON file and a MySQL database for additional processing in various sections of the site. Ideally, I aim to present the most recent data obtained (i.e., when the file is updated) to the client as soon as it is received.
Despite the fact that Channels are specifically designed for this type of functionality, I am encountering difficulties in implementation.
I have experimented with sending multiple requests from the client-side with delays and loops in the consumer, but it seems to only update upon refreshing or instantly. However, neither of these methods respond to changes in the file or database.
The following code technically "functions," but does not effectively fulfill the required task. (admittedly, there is minimal substance...)
# consumers.py
def ws_connect(message):
message.reply_channel.send({"accept": True})
def ws_receive(message):
with open("data.json") as jsonfile:
jsondata = json.load(jsonfile)
res = json.dumps(jsondata)
message.reply_channel.send({ "text": res, })
#routing.py
from channels.routing import route
from .consumers import ws_receive, ws_connect
channel_routing = [
route("websocket.receive", ws_receive, path=r"^/websockets/$"),
route("websocket.connect", ws_connect, path=r"^/websockets/$"),
]
Javascript utilized:
<script>
var wsurl = "ws://" + "mywebsite.com" + "/websockets/";
socket = new WebSocket(wsurl);
socket.onopen = function() {
socket.send("this is a request");
console.log('sent');
}
socket.onmessage = function(message) {
console.log(message.data);
document.getElementById("livedata").innerHTML = message.data;
}
</script>
I would greatly appreciate any guidance pointing towards documentation that could assist me in achieving a similar functionality, as I have been unable to find a solution after researching for an entire week.