skip to Main Content

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


  1. self.accept() is asynchronous, so it should be:

    await self.accept()
    
    Login or Signup to reply.
  2. from channels.db import database_sync_to_async

    class ChatConsumer(AsyncWebsocketConsumer):
        """ handshake websocket front end """
    
        room_name = None
        room_group_name = None
    
        async def connect(self):
            self.room_name = self.scope['url_route']['kwargs']['room_name']
            self.room_group_name = 'chat_%s' % self.room_name
    
            """Creating a new variable """
    
            self.botname = await database_sync_to_async(self.get_name)()
    
            print(self.botname)
       
    
            # Join room group
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )
    
            await self.accept()
    
        """ Creating a Function """
        def get_name(self):
            return CustomUser.objects.filter(groups__id = self.room_name).filter(is_bot = True)[0].username
    
    

    may be, helpful for you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search