2017-08-14 41 views
0

the docs,allowed_hosts_only是一个装饰器,以确保连接起源在settings.ALLOWED_HOSTS。但是,我很难将其应用于基于类的消费者。该applying decorators部分解释了如何装饰添加到类:使用django频道allowed_hosts_only与基于类的消费者

from channels.generic.websockets import JsonWebsocketConsumer 
from channels.security.websockets import allowed_hosts_only 

class MyConsumer(JsonWebsocketConsumer): 
    ... 
    def get_handler(self, *args, **kwargs): 
     handler = super(MyConsumer, self).get_handler(*args, **kwargs) 
     return allowed_hosts_only(handler) # just 'return handler' works 

这是错误我得到:

[2017/08/14 02:32:05] WebSocket HANDSHAKING/[123.123.123.123:12345] 
[2017/08/14 02:32:05] WebSocket DISCONNECT/[123.123.123.123:12345] 
Exception in thread Thread-4: 
Traceback (most recent call last): 
    File "/usr/lib64/python2.7/threading.py", line 804, in __bootstrap_inner 
    self.run() 
    File "/home/user/env/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 175, in run 
    worker.run() 
    File "/home/user/env/lib/python2.7/site-packages/channels/worker.py", line 123, in run 
    raise ValueError("You cannot DenyConnection from a non-websocket.connect handler.") 
ValueError: You cannot DenyConnection from a non-websocket.connect handler. 

我应该如何来验证与基于消费类连接原点?

我以为AllowedHostsOnlyOriginValidator可能是一个混入,但源只是有allowed_hosts_only = AllowedHostsOnlyOriginValidator

回答

0

您已检查通道是否为WebSocket。您可以通过检查Channel的名称来完成此操作。您在Message上找到该实例。当名字是websocket.connect你用修饰器allowed_hosts_only修饰处理程序。

这是怎么了你get_handler应该是这样的:

def get_handler(self, message, **kwargs): 
    handler = super(KioskConsumer, self).get_handler(message, **kwargs) 
    if self.message.channel.name == "websocket.connect": 
     handler = allowed_hosts_only(handler) 
    return handler 
+1

只是倾销代码块不是我们期望的质量。请解释此代码的作用。 – rene

+0

对不起,我不打算,我只是没有时间去达到你期望的质量,而我只是免费提供我的小知识。你能先读一下这个问题吗?有一个名为get_handler的方法,错误说错误值是ValueError:你不能从非websocket.connect处理程序中进行DenyConnection正如任何程序员可以从我的代码中看到的那样,它只是满足要求的一个新条件。 –

+0

没问题,我借机解释了你的代码的功能。 – rene

相关问题