I had a Django app that had live chat working. Now I am trying to add a query to the database within the connect
method. I am following the Channels documentation, and tried the solution in this other StackOverflow question but nothing is working.
Below is my code. The error I’m seeing in the Javascript console is `WebSocket connection to ‘ws://localhost:9008/ws/chat/334/’ failed: WebSocket is closed before the connection is established. I do have redis-server running on localhost and that was working before, so that’s not a problem.
async def connect(self):
print('connect (got here!)')
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
print('self.room_name: ' + str(self.room_name))
valid_connection = await database_sync_to_async(self.verify_chat_room_key)()
print('valid_connection: ' + str(valid_connection))
# Join room group
# async_to_sync(self.channel_layer.group_add)(
# self.room_group_name,
# self.channel_name
# )
await self.accept()
def verify_chat_room_key(self):
print('~~~in verify method...~~~')
return True
Edit: Below is the stacktrace showing the python debugs:
HTTP GET /confirmed-trade/334/ 200 [1.28, 127.0.0.1:53877]
WebSocket HANDSHAKING /ws/chat/334/ [127.0.0.1:58882]
HTTP GET /static/favicon.png 200 [0.01, 127.0.0.1:53877]
WebSocket HANDSHAKING /ws/chat/334/ [127.0.0.1:59246]
WebSocket DISCONNECT /ws/chat/334/ [127.0.0.1:59246]
disconnect
WebSocket HANDSHAKING /ws/chat/334/ [127.0.0.1:65175]
WebSocket DISCONNECT /ws/chat/334/ [127.0.0.1:58882]
disconnect
WebSocket DISCONNECT /ws/chat/334/ [127.0.0.1:65175]
disconnect
2
Answers
self.accept()
is asynchronous, so it should be:may be, helpful for you