[英]How to get django user after channels.Demultiplexer?
I'm trying to build user related websocket service with Django Channels. 我正在尝试使用Django Channels建立与用户相关的websocket服务。 I have this Demultiplexer at first line of my routing.py:
我在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):
So, now i writing consumers in routing.py: 所以,现在我在routing.py中编写使用者:
route('user.tracking', another_app.myconsumer),
or 要么
route_class(another_app.MyConsumer),`
and they hasn't message.user in input. 并且他们在输入中没有message.user。
Do i need call channel_session_user_from_http again? 我是否需要再次致电channel_session_user_from_http? Is there any reliable way to append user in Demultiplexer?
有什么可靠的方法可以在解复用器中追加用户?
I had similar problem with accessing user in my consumer function and I ended up decorating it with 我在使用者功能中访问用户时遇到了类似的问题,最终用
@channel_session_user
def ws_my_consumer(message):
I didn't find a way to do it using my custom Demultiplexer class. 我没有找到使用自定义解复用器类的方法。 I'm not so sure that there exists another solution because even the documentation mentions using decorators in the hooked consumers
我不太确定是否存在另一种解决方案,因为即使文档中也提到了在挂钩的使用者中使用装饰器
Option 1 - Get user in Demultiplexer 选项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
Option 2 - Get user in JsonWebsocketConsumer subclass 选项2-在JsonWebsocketConsumer子类中获取用户
from channels.generic.websockets import WebsocketDemultiplexer
from foo.consumers import WsFooConsumer
class Demultiplexer(WebsocketDemultiplexer):
consumers = {
"notifications": WsFooConsumer,
}
foo.consumers 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.