Django 从外部消费者发送数据 class
Django sending data from outside consumer class
我正在尝试使用 Django 通道通过 websocket 将数据从 Django 发送到我的 React 本机应用程序。我已经阅读了 Django 上有关此主题的所有可用文档,并浏览了许多 Whosebug 帖子,但我认为它们不适用于我,因为它们使用 redis 而我决定不使用 redis。
每当我现在尝试发送数据时,都没有发送任何数据。
这些是我的文件。
models.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
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer"
}
}
consumers.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")
我想做的是,每当我的数据库中存储一个新值时,我都会尝试通过连接我的本机反应应用程序和我的 django 后端的 websocket 发送消息。 Websocket 目前连接正常,但我无法从 consumers.py 外部使用我的 consumers.py 文件中包含的 send_message 函数。所以我想做的是在我的 models.py 文件中,向所有打开的通道发送一条消息,最终更新我的数据库。目前,我只是想通过发送测试消息,但无论我做什么,都没有通过,作为 Django 的新手,我不知道为什么。
谢谢!
在朋友的帮助下解决了!
consumers.py
`导入json
来自 channels.generic.websocket 导入 AsyncJsonWebsocketConsumer
从 .models 导入客户端
从 asgiref.sync 导入 sync_to_async
#已用 https://blog.logrocket.com/django-channels-and-websockets/
#https://channels.readthedocs.io/en/latest/topics/consumers.html
class DBUpdateConsumer(AsyncJsonWebsocketConsumer):
异步定义连接(自我):
print("频道名称是" + self.channel_name)
等待 sync_to_async(Client.objects.create)(channel_name=self.channel_name)
等待 self.accept()
等待self.send(text_data=json.dumps({
“有效载荷”:“更新”,
}))
打印(“连接!”)
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
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'
我正在尝试使用 Django 通道通过 websocket 将数据从 Django 发送到我的 React 本机应用程序。我已经阅读了 Django 上有关此主题的所有可用文档,并浏览了许多 Whosebug 帖子,但我认为它们不适用于我,因为它们使用 redis 而我决定不使用 redis。
每当我现在尝试发送数据时,都没有发送任何数据。
这些是我的文件。
models.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
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer"
}
}
consumers.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")
我想做的是,每当我的数据库中存储一个新值时,我都会尝试通过连接我的本机反应应用程序和我的 django 后端的 websocket 发送消息。 Websocket 目前连接正常,但我无法从 consumers.py 外部使用我的 consumers.py 文件中包含的 send_message 函数。所以我想做的是在我的 models.py 文件中,向所有打开的通道发送一条消息,最终更新我的数据库。目前,我只是想通过发送测试消息,但无论我做什么,都没有通过,作为 Django 的新手,我不知道为什么。
谢谢!
在朋友的帮助下解决了!
consumers.py
`导入json 来自 channels.generic.websocket 导入 AsyncJsonWebsocketConsumer 从 .models 导入客户端 从 asgiref.sync 导入 sync_to_async
#已用 https://blog.logrocket.com/django-channels-and-websockets/ #https://channels.readthedocs.io/en/latest/topics/consumers.html
class DBUpdateConsumer(AsyncJsonWebsocketConsumer): 异步定义连接(自我): print("频道名称是" + self.channel_name) 等待 sync_to_async(Client.objects.create)(channel_name=self.channel_name) 等待 self.accept() 等待self.send(text_data=json.dumps({ “有效载荷”:“更新”, })) 打印(“连接!”)
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
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'