如何允许 Channels 消费者访问 HTTP 请求生成的会话?

发布于 2025-01-15 18:12:48 字数 775 浏览 1 评论 0原文

我有一个项目曾经在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫弦 2025-01-22 18:12:48

没关系;这是一个愚蠢的错误。

如果其他人将来遇到同样的困惑,这里有一个解决方案的参考:在 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 using localhost. As a result, the cookies were not exposed.

Channels provides access to session objects just fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文