简体   繁体   English

Django 从外部消费者 class 发送数据

[英]Django sending data from outside consumer class

I am trying to get use Django channels to send data over a websocket to my react native application from django.我正在尝试使用 Django 通道通过 websocket 将数据发送到来自 django 的我的反应本机应用程序。 I have read all the available documentation on this subject on Django and have went through numerous stackoverflow posts, but I don't think they are applicable to me because they use redis and I decided not to use redis.我已阅读 Django 上有关此主题的所有可用文档,并阅读了许多 stackoverflow 帖子,但我认为它们不适用于我,因为它们使用 redis,我决定不使用 Z86A1B907D64BF70107ZE.BFE316

Whenever I try to send data right now, nothing sends.每当我现在尝试发送数据时,什么都没有发送。

These are my files.这些是我的文件。

models.py模型.py

from django.db import models
import json
from .consumers import DBUpdateConsumer
from django.db.models.signals import post_save
from django.dispatch import receiver
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync



channel_layer = get_channel_layer()


class Connect(models.Model):
    id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    neighborhood = models.CharField(max_length=50, choices=neighborhood_choices, default='all')
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=100)
    phone = models.CharField(max_length=50)

    def save(self, *args, **kwargs):
        super().save(self, *args, **kwargs)
        print("def save")
        async_to_sync(channel_layer.send)("hello", {"type": "something", "text": "hellooo"})


    class Meta:
        managed = False
        db_table = 'connect'

settings.py设置.py

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    }
}

consumers.py消费者.py

import json
from channels.generic.websocket import AsyncJsonWebsocketConsumer


#used https://blog.logrocket.com/django-channels-and-websockets/
#https://channels.readthedocs.io/en/latest/topics/consumers.html

class DBUpdateConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.send_message(self, "UPDATE")

        
        await self.accept()

        await self.send(text_data=json.dumps({
            "payload": "UPDATE",
        }))
        print("connect!")

    async def disconnect(self, close_code):
        print("Disconnected")
        

    async def receive(self, text_data):
        """
        Receive message from WebSocket.
        Get the event and send the appropriate event
        """
        response = json.loads(text_data)
        #event = response.get("event", None)
        #message = response.get("message", None)

        print(response)
       

    @classmethod
    async def send_message(cls, self, res):
        # Send message to WebSocket
        print("send msg")
        await self.send(text_data=json.dumps({
            "payload": res,
        }))
        print("send msg")

What I am trying to do is whenever a new value is stored in my database, I am trying to send a message through a websocket that connects my react native app and my django backend.我想要做的是每当一个新值存储在我的数据库中时,我都会尝试通过连接我的反应本机应用程序和我的 django 后端的 websocket 发送消息。 The websocket currently connects fine, but I am having trouble using the send_message function contained within my consumers.py file from outside consumers.py. websocket 目前连接良好,但我在使用来自外部consumers.py 的consumers.py 文件中包含的send_message function 时遇到问题。 So what I am trying to do is in my models.py file, send a message to all the channels that are open to eventually update my database.所以我要做的是在我的 models.py 文件中,向所有打开的通道发送一条消息,以最终更新我的数据库。 Currently, I am just trying to send test messages through, but no matter what I do, nothing goes through, and being a newbie to Django, I have no idea why.目前,我只是想通过发送测试消息,但无论我做什么,都没有通过,作为 Django 的新手,我不知道为什么。

Thank you!谢谢!

Solved, with some help from a friend!在朋友的帮助下解决了!

consumers.py消费者.py

import json
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from .models import Client
from asgiref.sync import sync_to_async

#used https://blog.logrocket.com/django-channels-and-websockets/
#https://channels.readthedocs.io/en/latest/topics/consumers.html

class DBUpdateConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        print("channel name is " + self.channel_name)
        await sync_to_async(Client.objects.create)(channel_name=self.channel_name)
        await self.accept()
        await self.send(text_data=json.dumps({
            "payload": "UPDATE",
        }))
        print("connect!")

    async def disconnect(self, close_code):
        print("Disconnected")
        # Leave room group
        """await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )"""

    async def update(self, message):
        print("Sent message " + message["text"])
        await self.send(text_data=json.dumps({
            "payload": "UPDATE",
        }))

    async def receive(self, text_data):
        """
        Receive message from WebSocket.
        Get the event and send the appropriate event
        """
        response = json.loads(text_data)
        #event = response.get("event", None)
        #message = response.get("message", None)

        print(response)
        """if event == 'MOVE':
            # Send message to room group
            await self.channel_layer.group_send(self.room_group_name, {
                'type': 'send_message',
                'message': message,
                "event": "MOVE"
            })

        if event == 'START':
            # Send message to room group
            await self.channel_layer.group_send(self.room_group_name, {
                'type': 'send_message',
                'message': message,
                'event': "START"
            })

        if event == 'END':
            # Send message to room group
            await self.channel_layer.group_send(self.room_group_name, {
                'type': 'send_message',
                'message': message,
                'event': "END"
            })"""

    # @classmethod
    # async def send_message(cls, self, res):
    #     # Send message to WebSocket
    #     print("send msg")
    #     await self.send(text_data=json.dumps({
    #         "payload": res,
    #     }))
    #     print("send msg")

models.py模型.py

class Connect(models.Model):
    id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    neighborhood = models.CharField(max_length=50, choices=neighborhood_choices, default='all')
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=100)
    phone = models.CharField(max_length=50)

    def save(self, *args, **kwargs):
        super().save(self, *args, **kwargs)
        clients = Client.objects.all()
        for client in clients:
            async_to_sync(channel_layer.send)(client.channel_name, {"type": "update", "text": "hellooo"})

    class Meta:
        managed = False
        db_table = 'connect'

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

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