How to Access URL Params in Django Channels Consumers
Question:
If i had the following url in routing.py:
/rooms/<int:id>/
How would I access the id parameter from withing a JSONWebsocketConsumer?
Answers:
this.scope['url_path']['kwargs']['id']
I think the documentation needs updating, ‘url_path’ didn’t work for me, but ‘url_route’ did.
self.scope['url_route']['kwargs']['id']
To access any query param you can use;
for example socket URL = ws://localhost:8000/notifications?id=11
from urllib.parse import parse_qsl
query_params = dict(parse_qsl(self.scope['query_string'].decode('utf-8')))
print(query_params['id'])
Get ID from the query param using;
self.scope['path'].split('/')[-2]
If i had the following url in routing.py:
/rooms/<int:id>/
How would I access the id parameter from withing a JSONWebsocketConsumer?
this.scope['url_path']['kwargs']['id']
I think the documentation needs updating, ‘url_path’ didn’t work for me, but ‘url_route’ did.
self.scope['url_route']['kwargs']['id']
To access any query param you can use;
for example socket URL = ws://localhost:8000/notifications?id=11
from urllib.parse import parse_qsl
query_params = dict(parse_qsl(self.scope['query_string'].decode('utf-8')))
print(query_params['id'])
Get ID from the query param using;
self.scope['path'].split('/')[-2]