Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 拒绝使用django频道访问未经身份验证的用户_Python_Django_Django Channels - Fatal编程技术网

Python 拒绝使用django频道访问未经身份验证的用户

Python 拒绝使用django频道访问未经身份验证的用户,python,django,django-channels,Python,Django,Django Channels,对于django频道,我基本上需要login\u所需的/LoginRequiredMixin等同物。文档中有一个描述如何获取用户的名称,但它似乎忽略了您实际上拒绝未经身份验证的用户访问的部分 from channels.generic.websockets import JsonWebsocketConsumer class MyConsumer(JsonWebsocketConsumer): channel_session_user = True def connecti

对于django频道,我基本上需要
login\u所需的
/
LoginRequiredMixin
等同物。文档中有一个描述如何获取用户的名称,但它似乎忽略了您实际上拒绝未经身份验证的用户访问的部分

from channels.generic.websockets import JsonWebsocketConsumer

class MyConsumer(JsonWebsocketConsumer):

    channel_session_user = True

    def connection_groups(self, **kwargs):
        return ["test"]

    def connect(self, message, **kwargs):
        print message.user # AnonymousUser
        self.send({"accept": True}) # False here still accepts and sends a message
如果
message.user.is\u anonymous
为真,我应该如何拒绝/删除连接?

只需执行以下操作:

if user.is_authenticated():
    # allow it

尝试连接时拒绝连接很简单:如果不想建立连接,则根本不发送接受消息。通道将在配置的时间后自动关闭(默认情况下为5秒或smth)

如果不想等待并立即关闭连接,只需发送
{“close”:True}

def connect(self, message, **kwargs):
    if not message.user.is_anonymous:
        self.send({"accept": True})
    else:
        self.send({"close": True})

为了完整起见,下面是来自的解释。遗憾的是,这些信息没有在文档本身中列出,只在v1.0的发行说明中列出。

只是为了澄清,
AnonymousUser.is\u authenticated
将始终返回false?我的问题是如何禁止它。一个通道可以关闭还是需要等待超时?@jozxyqk:当然,如果你想显式关闭连接并且不想等待
通道关闭它,发送
{“close”:True}
,而不是
{“accept”:True}
。我会更新答案。
def connect(self, message, **kwargs):
    if not message.user.is_anonymous:
        self.send({"accept": True})
    else:
        self.send({"close": True})