D
D
Durilka962022-03-05 00:07:48
Django
Durilka96, 2022-03-05 00:07:48

Why doesn't websocket see the url?

why it doesn’t go through routing, in the browser I watch json is sent, and then immediately disconnect happens.
62227f853da44340367782.png
chats.html
create a websocket

const create_dialog_Socket = new WebSocket(
                'ws://'
                + window.location.host
                + '/ws/'
                + 'dialog_'
                + uniqua_dialog_id
                + '/'
            );

routing.py
I think that somehow I read the link incorrectly in this place
websockets_urlpatterns = [
    path('ws/<str:chat_name>/', consumers.ChatConsumer.as_asgi()),
    path('ws/<str:dialog_id>/', consumers.AddChatsConsumer.as_asgi()),
]

consumers.py
class AddChatsConsumer (AsyncWebsocketConsumer):



    async def connect(self):
        self.dialog_id = self.scope['url_route']['kwargs']['dialog_id']
        print("зашло")
        self.uniqua_dialog_id = self.dialog_id
        await self.channel_layer.group_add(
            self.uniqua_dialog_id,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self):
        await self.channel_layer.group_discard(
            self.uniqua_dialog_id,
            self.channel_name
        )

    async def receive(self, text_data):
        data = json.loads(text_data)
        name = data['name']
        name_2 = data['name_2']


        await self.save_create_chats(name, name_2)

        await self.channel_layer.group_send(
            self.uniqua_dialog_id,
            {
                'type': 'create_chats',
                'name': name,
                'name_2': name_2,


            }
        )

    async def create_chats(self, event):
        name = event['name']
        name_2 = event['name_2']


        await self.send(text_data=json.dumps({
            'name': name,
            'name_2': name_2,

        }))

    @sync_to_async
    def save_create_chats(self, name, name_2):
        print("зашло")
        slug=0
        Chats.objects.create( name = name, name_2=name_2, slug=slug)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2022-03-05
@bacon

well, how do you distinguish the url for AddChatsConsumer from ChatConsumer in routing.py?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question