繁体   English   中英

如何在Channels.Demultiplexer之后获得django用户?

[英]How to get django user after channels.Demultiplexer?

我正在尝试使用Django Channels建立与用户相关的websocket服务。 我在routing.py的第一行有这个解复用器:

def checkauth(f):
    def wrapper(*args, **kwargs):        
        if args[0].message.user.is_anonymous():
            args[0].send(stream="auth", payload = {'m':'pissoff'})
            args[0].close()
            return
        return f(*args, **kwargs)
    return wrapper


class Demultiplexer(WebsocketDemultiplexer):
    http_user = True

    mapping = {"auth": "user.tracking",}

    @checkauth
    def connect(self, message, **kwargs):

    @checkauth
    def receive(self, content, **kwargs):

所以,现在我在routing.py中编写使用者:

route('user.tracking', another_app.myconsumer), 

要么

route_class(another_app.MyConsumer),` 

并且他们在输入中没有message.user。

我是否需要再次致电channel_session_user_from_http? 有什么可靠的方法可以在解复用器中追加用户?

我在使用者功能中访问用户时遇到了类似的问题,最终用

@channel_session_user
def ws_my_consumer(message):

我没有找到使用自定义解复用器类的方法。 我不太确定是否存在另一种解决方案,因为即使文档中也提到了在挂钩的使用者中使用装饰器

选项1-在解复用器中获取用户

from channels.generic.websockets import WebsocketDemultiplexer
from foo.consumers import WsFooConsumer

class Demultiplexer(WebsocketDemultiplexer):
    http_user = True

    consumers = {
        "foo": WsFooConsumer,
    }

    def connect(self, content, **kwargs):
        print self.message.user


选项2-在JsonWebsocketConsumer子类中获取用户

from channels.generic.websockets import WebsocketDemultiplexer
from foo.consumers import WsFooConsumer


class Demultiplexer(WebsocketDemultiplexer):
    consumers = {
        "notifications": WsFooConsumer,
    }

foo.consumers

from channels.generic.websockets import JsonWebsocketConsumer

class WsFooConsumer(JsonWebsocketConsumer):
    http_user = True

    def connect(self, message, multiplexer, **kwargs):
        print message.user

    def disconnect(self, message, multiplexer, **kwargs):
        print message.user

    def receive(self, content, multiplexer, **kwargs):
        print self.message.user

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM