简体   繁体   English

如何从消费者 django 通道外部将数据发送到 websocket

[英]How to send data to a websocket from outside of consumer django channels

I'm trying to send data to a websocket from outside of the consumer我正在尝试从消费者外部将数据发送到 websocket

so i did following:所以我做了以下事情:

settings.py设置.py

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

routing.py路由.py

from django.urls import path

from .consumers import CoinsListConsumer

websocket_urlpatterns = [
    path('ws/coins/', CoinsListConsumer.as_asgi())
]

asgi.py asgi.py

import os

from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator

from apps.coins.routing import websocket_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local')

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                websocket_urlpatterns,
            )
        )
    )
})

consumers.py消费者.py

class CoinsListConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        logger.info('Websocket was connected.')
        await self.accept()
    
    async def disconnect(self, code):
        logger.warning('Websocket was disconnected.')
        pass

    async def receive(self, text_data=None, bytes_data=None):
        return await super().receive(text_data, bytes_data)

well this is ok and when i go to a view... the websocket will connect very well好吧,这没关系,当我去看风景时...... websocket 将连接得很好

but when i want to send data to the websocket.但是当我想将数据发送到 websocket 时。

def send_data_to_websocket_coins_list_view(data: List[Dict]) -> None:
    """Send data to websocket coins list view """
    async_to_sync(channel_layer.send)(json.dumps(data))

This did not work and raised following error TypeError: send() missing 1 required positional argument: 'message'这不起作用并引发以下错误TypeError: send() missing 1 required positional argument: 'message'

Also in the documentation this is should work by following code同样在文档中,这应该通过以下代码工作

async_to_sync(channel_layer.send)("channel_name", json.dumps({...}))

its also not worked and raise the following error AssertionError: message is not a dict它也不起作用并引发以下错误AssertionError: message is not a dict

So what is the problem?那么问题是什么? what should i do?我应该怎么办?

你不需要转储数据

async_to_sync(channel_layer.send)(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM