djangowebsocketdjango-channels

UUID breaking the ws connect


I've been using a websockets connection with django-channels for a chatroom app with the following routing:

    re_path(r'ws/chat/(?P<room_name>\w+)/participant/(?P<user>\w+)/$', consumers.ChatConsumer.as_asgi())

So if the id of my chatroom is 1, to connect to WS I would use the following url with 2 being the id of the participant that wants to enter the room:

ws/chat/1/participant/1/

Now i changed the id of my room model to UUID so now to connect to a room I need to use the following url

ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/

where "84f48468-e966-46e9-a46c-67920026d669" is the id of my room now, but I'm getting the following error:

raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'ws/chat/84f48468-e966-46e9-a46c- 
67920026d669/participant/1/'.
WebSocket DISCONNECT /ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/ 
[127.0.0.1:50532]

My consumers:

class ChatConsumer(WebsocketConsumer):
def connect(self):
    self.room_name = self.scope['url_route']['kwargs']['room_name']
    self.user = self.scope['url_route']['kwargs']['user']
    self.room_group_name = 'chat_%s' % self.room_name
    

    # Join room group
    async_to_sync(self.channel_layer.group_add)(
        self.room_group_name,
        self.channel_name
    )

    
    
    self.accept()

    

def disconnect(self, close_code):
    delete = delete_participant(self.room_name, self.user)
    if delete == 'not_can_delete_user':
        pass
    else:
        # Leave room group
        channel_layer = get_channel_layer()    
        async_to_sync(channel_layer.group_send)(
            f'chat_{self.room_name}',
            {
                'type': 'receive',
                'message': "USER_DISCONNECT",
                'body': {
                    'participant': delete,
                    'idParticipant': self.user
                }
            }
        )
    
    async_to_sync(self.channel_layer.group_discard)(
        self.room_group_name,
        self.channel_name
    )

    
    
    
    
def receive(self, text_data=None, type='receive', **kwargs):
    if isinstance(text_data, dict):
        text_data_json = text_data
        
        message = text_data_json['message']
        body = text_data_json['body']
    else:
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        body = text_data_json['body']
    
    self.send(text_data=json.dumps({
        'message': message,
        "body": body 
                    
        }))
        
    

What is wrong?


Solution

  • try this regex:

     re_path(r'ws/chat/(?P<room_name>[A-Za-z0-9_-]+)....