python - 如何从 Django Channels 网络套接字数据包中获取当前用户?

标签 python django sockets session django-channels

我正在学习本教程:Finally, Real-Time Django Is Here: Get Started with Django Channels .

我想通过使用 Django User 对象而不是 handle 变量来扩展应用程序。 但是我如何从我的 ws_recieve(message) 函数中接收到的 WebSocket 数据包中获取当前用户?

我注意到网络套接字数据包中的 csrftokensessionid 的前十位数字都匹配正常的 HTTP 请求。我可以获得当前用户的这些信息吗?

作为引用,接收到的数据包如下所示:

{'channel': <channels.channel.Channel object at 0x110ea3a20>,
 'channel_layer': <channels.asgi.ChannelLayerWrapper object at 0x110c399e8>,
 'channel_session': <django.contrib.sessions.backends.db.SessionStore object at 0x110d52cc0>,
 'content': {'client': ['127.0.0.1', 52472],
             'headers': [[b'connection', b'Upgrade'],
                         [b'origin', b'http://0.0.0.0:8000'],
                         [b'cookie',
                          b'csrftoken=EQLI0lx4SGCpyTWTJrT9UTe1mZV5cbNPpevmVu'
                          b'STjySlk9ZJvxzHj9XFsJPgWCWq; sessionid=kgi57butc3'
                          b'zckszpuqphn0egqh22wqaj'],
                         [b'cache-control', b'no-cache'],
                         [b'sec-websocket-version', b'13'],
                         [b'sec-websocket-extensions',
                          b'x-webkit-deflate-frame'],
                         [b'host', b'0.0.0.0:8000'],
                         [b'upgrade', b'websocket'],
                         [b'sec-websocket-key', b'y2Lmb+Ej+lMYN+BVrSXpXQ=='],
                         [b'user-agent',
                          b'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '
                          b'AppleWebKit/602.1.50 (KHTML, like Gecko) Version'
                          b'/10.0 Safari/602.1.50'],
                         [b'pragma', b'no-cache']],
             'order': 0,
             'path': '/chat-message/',
             'query_string': '',
             'reply_channel': 'websocket.send!UZaOWhupBefN',
             'server': ['127.0.0.1', 8000]},
 'reply_channel': <channels.channel.Channel object at 0x110ea3a90>}

最佳答案

2018 年更新答案 via the docs :

To access the user, just use self.scope["user"] in your consumer code:

class ChatConsumer(WebsocketConsumer):

    def connect(self, event):
        self.user = self.scope["user"]

    def receive(self, event):
        username_str = None
        username = self.scope["user"]
        if(username.is_authenticated()):
            username_str = username.username
            print(type(username_str))
            #pdb.set_trace() # optional debugging

关于python - 如何从 Django Channels 网络套接字数据包中获取当前用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40005701/

相关文章:

python - random.random() 在 for 循环中产生相同的结果

python - 运行代码时为 "pygame.error: display Surface quit"

python - numpy.where 与 like 运算符

python - 在 View 中访问 c​​ontext_dict

c# - 从 UDP 连接 C# 获取客户端 ip

Android 连接有时会被拒绝(并非所有时候)

python - 在 python 脚本中使用 Qt Designer 文件

django - 禁用字段未通过 - 需要解决方法

linux - 接受/轮询问题

python - 当使用 nginx 作为 gunicorn 的反向代理时,Django 应用程序中的空 REMOTE_ADDR 值