I'm trying to build user related websocket service with Django Channels. I have this Demultiplexer at first line of my 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:
route('user.tracking', another_app.myconsumer),
or
route_class(another_app.MyConsumer),`
and they hasn't message.user in input.
Do i need call channel_session_user_from_http again? 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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.