我需要从Django Channels访问查询参数dict。
网址可能如下所示:ws://127.0.0.1:8000/?hello="world"
如何像这样检索'世界':query_params["hello"]
?
答案 0 :(得分:6)
在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]
入门文档(http://channels.readthedocs.io/en/stable/getting-started.html)意味着query_string作为message.content路径的一部分包含在内,但它似乎并非如此。
以下是聊天应用程序示例的一个有效的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)
答案 1 :(得分:1)
针对第 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])
如果你经常这样做,你可以把它放在一个中间件中,并将你的 ASGI 应用程序包装在其中。类似的东西:
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)