0

我正在尝试使用 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 吗?有没有可靠的方法在解复用器中附加用户?

4

2 回答 2

0

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

@channel_session_user
def ws_my_consumer(message):

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

于 2016-08-10T18:35:18.337 回答
0

选项 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
于 2017-02-07T18:46:08.157 回答