问题
I have a django app that carries out some calculations on the server which can take up to 30 seconds. I am trying to use django channels to create a progress indicator.
My setup is based on this tutorial: https://realpython.com/blog/python/getting-started-with-django-channels/
Everything is working as expected so far. I submit a task by web socket. This is received by my consumer, which calls other methods to complete the task, then returns the result by websocket.
However, when I try to send multiple messages from the same consumer, all the messages arrive together at the end, rather than arriving when they are sent.
Here is my consumer code:
@channel_session
def ws_receive(message):
data = json.loads(message['text'])
reply_channel = message.reply_channel.name
Channel(reply_channel).send({
"text": json.dumps({'progress': 'Starting Work'})
})
# calls outside method to do work
result = perform_calculations(data, reply_channel)
Channel(reply_channel).send({
"text": json.dumps({'progress': 'Finished Work','result':result })
})
In this example, my front end receives the 'Starting Work' and 'Finished Work' messages at the same time, even though there is a 30 second gap between them being generated.
Is there a way to get these messages to arrive in real time?
回答1:
Yes there is, you could use the immediately parameter.
Channel(message.reply_channel).send({
"text": json.dumps({'progress': 'Starting Work'})
}, immediately=True)
Also mentioned at:
How do I ensure a Django Channels message is sent immediately without delay?
回答2:
You can to take a look to this project:
https://gitlab.com/Baurin_lg/demo_channels_rest
It's a demo to use Django Rest and Django Channels.
来源:https://stackoverflow.com/questions/43284460/using-django-channels-for-a-progress-indicator