如何允许 Channels 消费者访问 HTTP 请求生成的会话?
我有一个项目曾经在 WSGI 下运行,最近我将其配置为 ASGI。它包含当时的代码,例如以下处理登录请求的函数:
def authenticate(req):
...
try:
query = models.User.objects.get(...)
req.session['user'] = query.id #Login successful
...
except:
#No record, reject request
...
我现在要做的是创建一个 WebsocketConsumer 并从内部访问会话。我已启用 SessionMiddlewareStack。问题是消费者甚至看不到会话,因为会话的 ID 没有作为标头附加到 WebSocket 请求中。有没有办法让它访问数据?
class SpaceConsumer(WebsocketConsumer):
def connect(self):
#Session object is empty, while HTTP requests see it as populated with the user's ID
if 'user' in self.scope['session']:
self.accept() #Only allow authenticated user
在线信息很少,大多数都是为旧版本的 Channels 编写的。我正在使用 Channels v3。
I have a project that used to run under WSGI, and I recently configured it to ASGI. It included code from back then, such as the following function that processes a login request:
def authenticate(req):
...
try:
query = models.User.objects.get(...)
req.session['user'] = query.id #Login successful
...
except:
#No record, reject request
...
What I want to do now is to create a WebsocketConsumer and access the session from within. I have enabled SessionMiddlewareStack. The problem is that the consumer does not even see the session because the session's ID is not attached to the WebSocket request as a header. Is there a way to allow it to access the data?
class SpaceConsumer(WebsocketConsumer):
def connect(self):
#Session object is empty, while HTTP requests see it as populated with the user's ID
if 'user' in self.scope['session']:
self.accept() #Only allow authenticated user
Information online is scarce, and most are written for older versions of Channels. I am using Channels v3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没关系;这是一个愚蠢的错误。
如果其他人将来遇到同样的困惑,这里有一个解决方案的参考:在 websocket 握手中使用会话数据。
您创建 Websocket 连接的域必须与您的页面的域匹配。就我而言,我使用
127.0.0.1
打开应用程序,但使用localhost
连接到 WS。结果,cookies没有被暴露。通道提供了对会话对象的访问。
Never mind; it was a stupid mistake.
In case other people come here in the future with the same confusion, here is a reference to a solution: Use session data on websocket handshake.
The domain with which you create a Websocket connection must match that of your page. In my case, I opened the application using
127.0.0.1
but connected to WS usinglocalhost
. As a result, the cookies were not exposed.Channels provides access to session objects just fine.