Django Channels-在Shell命令级别将数据发送到套接字

时间:2018-08-08 03:27:21

标签: python django django-channels

我想将数据发送到class ChatConsumer之外的前端套接字。这是我的consumer.py

class ChatConsumer(AsyncConsumer):
    async def ws_connect(self, event):
        self.send = get_db_object()

        ....

        await self.send({
            "type": "websocket.accept"
        })

    # I need to CONSTANTLY receive & send data
    async def ws_receive(self, event):

        obj = ...# query DB and get the newest object

        json_obj = {
            'field_1': obj.field_1,
            'field_2': obj.field_2,
        }

        await self.send({
            "type": "websocket.send",
            "text": json.dumps(json_obj)
        })

还有我的routing.py

from chat.consumers import ChatConsumer
application = ProtocolTypeRouter({
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    # the documentation used url(), so just stick to this instead of re_path
                    url(r"^messages/(?P<username>[\w.@+-]+)/$", ChatConsumer),
                ]
            )
        )

    )
})

如您所见,我的ChatConsumer在我的routing.py中被调用,在我的ChatConsumer内部,我可以使用await self.send({...})将数据发送到前端。但是,如果我想使用Shell Command将数据发送到当前打开的前端怎么办?

通过运行manage.py runserver假定端口已打开。我想使用Shell命令将数据提供给前端。我怎样才能做到这一点?如何获得与ChatConsumer在Shell级别具有的连接相同的连接?

0 个答案:

没有答案