问题
I'm using channels to long-poll a database so I'm using the AsyncConsumer
. I can't get the disconnect method to run when the webpage closes or is manually refreshed. I've tried creating;
def disconnect(self, close_code)
def ws_disconnect(self, close_code)
def websocket_disconnect(self, close_code)
I've tried them with and without async in front. I've also tried replacing the parameters with 'event'
.
When I first wrote the methods I included channels.exceptions.StopConsumer()
but when that didn't work I placed a print statement inside my disconnect method just for testing and it appears that the disconnect method is never firing.
Apologies if this is a stupid question but I've spent 3 days trying everything that I could find on the internet. When I close or refresh the page the terminal shows
'WebSocket DISCONNECT /page_name/ [127.0.0.1:35748]
and then a few seconds later there's a message which states
'Application instance <Task pending coro=<__call__() running at /home/ecl/.local/lib/python3.5/site-packages/channels/sessions.py:179> wait_for=<Future pending cb=[Task._wakeup()]>> for connection <WebSocketProtocol client=['127.0.0.1', 35746] path=b'/alertstatus/'> took too long to shut down and was killed.'
If anyone can give me any suggestions as to where to look for a solution to this I'd really appreciate it.
回答1:
You should raise StopConsumer().
My example:
from channels.exceptions import StopConsumer
...
async def websocket_disconnect(self, event):
# Leave room group
await self.channel_layer.group_discard(
self.room_name,
self.channel_name
)
raise StopConsumer()
it's work for me.
来源:https://stackoverflow.com/questions/53445286/django-channels-wont-disconnect