I'm building web-app with Django and Django Channels that utilizes websockets.
When user clicks the button in browser, websocket sends data to my server and consumer on the server starts to send messages to the client once per second (in loop).
I want to create another button that will stop this data sending process. When user clicks on this new button, websocket sends another data to server and consumer on the server must somehow stop the loop in previous consumer. Also I will require this to stop the loop when client disconnects.
I felt a desire to use global variable. But Django Channels documentation states that they strongly not recommend to use global variables as they want keep the app network transparent (don't really understand this).
I've tried to use channel session. I made second consumer to update value in channel session, but channel session values didn't get updated in first consumer.
Here is simplified code. Browser:
var socket = new WebSocket("ws://" + window.location.host + "/socket/");
$('#button1').on('click', function() {
socket.send(JSON.stringify({action: 'start_getting_values'}))
});
$('#button2').on('click', function() {
socket.send(JSON.stringify({action: 'stop_getting_values'}))
});
Consumer on server:
@channel_session
def ws_message(message):
text = json.loads(message.content['text'])
if text['action'] == 'start_getting_values':
while True:
# Getting some data here
# ...
message.reply_channel.send({"text": some_data}, immediately=True)
time.sleep(1)
if text['action'] == 'stop_getting_values':
do_something_to_stop_the_loop_above()