I need to maintain a connection of sockets on several pages, URLRouter 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 scope I need to get device_name to send it to another function, but for some reason I’m looking for it on all pages in URLRouter.So, for example, in/add, the socket is immediately closed, because it cannot find there device_name.

On the pages with the device everything works fine, on others I get the error: Exception inside application:'device_name'
  • Why not check for device_name? – Jackie72 Jul 27 '19 at 09:57
  • Jackie72, did, but something also did not work.In general, it seemed like a small crutch, the same example was written in the documentation and everything works
    if"device_name" in(self.scope['url_route']['kwargs']['device_name']):
                device_id=get_device_id((self.scope['url_route']['kwargs']['device_name']))

    Maybe something is wrong of course.It’s necessary to somehow exclude the check on device_name from the condition, because it still tries to find it on all travelers as soon as the connection opens
    – Plain Polecat Jul 27 '19 at 10:05
  • There is an error
    if"device_name" in(self.scope['url_route']['kwargs']['device_name']):

    It must be
    if"device_name" in self.scope['url_route']['kwargs']:
    – Jackie72 Jul 27 '19 at 10:25
  • Well, there is the same consumer for all URLs, of course, you need to check the presence of device_name, because it is only at one address out of 3x, and the consumer is called ONE and the same. – Jackie72 Jul 27 '19 at 10:26
  • Jackie72, Thank you.it came out with your condition, sort of like.Regarding Consumer - the documentation also has 2 different paths with one account, but the scope is working fine.A little confused me – Plain Polecat Jul 27 '19 at 10:29
  • Plain Polecat, well, so the scope And right now it is processed normally) but you always had a device_name there which sometimes may not be there. – Jackie72 Jul 27 '19 at 10:31

1 Answers 1

if'device_name'in self.scope['url_route']['kwargs']:
    self.device_id=self.get_device_id(self.scope['url_route']['kwargs']['device_name'])
    #here is the code for device_name
else:
    #here is the code for the remaining urls


and of course, there are more options...