[英]How to get query parameters from Django Channels?
I need to access the query parameter dict from Django Channels.我需要从 Django Channels 访问查询参数 dict。
The url may look like this: ws://127.0.0.1:8000/?hello="world"
网址可能如下所示:
ws://127.0.0.1:8000/?hello="world"
How do I retrieve 'world' like this: query_params["hello"]
?如何像这样检索“世界”:
query_params["hello"]
?
On a websocket connect the message.content dictionary contains the query_string.在 websocket 连接上,message.content 字典包含 query_string。
import urlparse
def ws_connect(message):
params = urlparse.parse_qs(message.content['query_string'])
hello = params.get('hello', (None,))[0]
The getting started documentation ( http://channels.readthedocs.io/en/stable/getting-started.html ) implies the query_string is included as part of the message.content path, but it doesn't appear to be the case.入门文档 ( http://channels.readthedocs.io/en/stable/getting-started.html ) 暗示 query_string 作为 message.content 路径的一部分包含在内,但似乎并非如此。
Below is a working consumer.py for the chat application sample where the room is passed in the query string:下面是聊天应用程序示例的工作 consumer.py,其中房间在查询字符串中传递:
import urlparse
from channels import Group
from channels.sessions import channel_session
@channel_session
def ws_message(message):
room = message.channel_session['room']
Group("chat-{0}".format(room)).send({"text": "[{1}] {0}".format(message.content['text'], room)})
@channel_session
def ws_connect(message):
message.reply_channel.send({"accept": True})
params = urlparse.parse_qs(message.content['query_string'])
room = params.get('room',('Not Supplied',))[0]
message.channel_session['room'] = room
Group("chat-{0}".format(room)).add(message.reply_channel)
@channel_session
def ws_disconnect(message):
room = message.channel_session['room']
Group("chat-{0}".format(room)).discard(message.reply_channel)
Updated for Channel 3:频道 3 更新:
from urllib.parse import parse_qs
# Types
class Scope(TypedDict):
query_string: bytes
scope: Scope
query_params: Dict[str, List[str]]
# Parse query_string
query_params = parse_qs(scope["query_string"].decode())
print(query_params["access_token"][-1])
If you were doing this a lot, you could put it in a middleware and wrap your ASGI application in it.如果你经常这样做,你可以把它放在一个中间件中,并将你的 ASGI 应用程序包装在其中。 Something like:
就像是:
class QueryParamsMiddleware(BaseMiddleware):
async def __call__(self, scope, receive, send):
scope = dict(scope)
scope["query_params"] = parse_qs(scope["query_string"].decode())
return await super().__call__(scope, receive, send)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.