A
A
Alisa Unylova2019-07-27 09:54:13
Django
Alisa Unylova, 2019-07-27 09:54:13

Scope in django_channels looks for argument on all pages from URLRouter, how to fix?

I need to support socket connection across multiple pages, the URLRouter is like this:

URLRouter([
    path('device/<device_name>',IndicatorConsumer),
    path('add',IndicatorConsumer),
    path('', IndicatorConsumer)
])

In consumers like this:
async def websocket_connect(self,event):
    print('connection succefull ', event)
    await self.send({
        'type': 'websocket.accept'
    })
    self.device_id = self.get_device_id(self.scope['url_route']['kwargs']['device_name'])

Through scopeI need to receive device_namein order to send it to another function, but for some reason the scope is looking for this on all the pages that are in URLRouter. So, for example, in /add the socket is immediately closed because it cannot find a device_name.
On pages with device everything works fine, on others I get an error:Exception inside application: 'device_name'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-07-27
@alisadvachee

if   'device_name' in self.scope['url_route']['kwargs']:
    self.device_id = self.get_device_id(self.scope['url_route']['kwargs']['device_name'])
    # тут код для device_name
else:
    # тут код для остальных урлов

And of course there are other options...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question