我是django-channels和python的新手,我用django-channels和django做了一个演示,主动地将数据从后台发送到前端。consumers.py中的代码如下:
websocket_clients = []
class WebsocketConsumer(AsyncWebsocketConsumer):
def __init__(self, *args, **kwargs):
"""
initial a new thread when new websocket instance initialed.
"""
super(WebsocketConsumer, self).__init__(self)
self.index_websocket = GendataThread()
async def connect(self):
self.index_websocket.channels_name = self.channel_name
print('channel_name', self.channel_name)
self.index_websocket.start()
websocket_clients.append(self.channel_name)
await self.accept()
async def disconnect(self, close_code):
"""disconnected a websocket instance, and stop the thread."""
self.index_websocket.stop()
time.sleep(2)
index = websocket_clients.index(self.channel_name)
websocket_clients.pop(index)
async def receive(self, text_data):
"""receive message from connected client, wouldn't work in this project."""
text_data = '{"message": "%s"}' % (text_data)
text_data_json = json.loads(text_data)
async def chat_message(self, event):
"""send message to websocket."""
print('event', event)
await self.send(text_data=json.dumps(
{'message': event['message']}))
def websocket_send_data(data, channel_name):
"""
send data to front in websocket protocol,
:param data: data which will be sent,
:param channel_name: a symbol to mark connected client.
:return:
"""
channel_layer = get_channel_layer()
event = {
"type": "chat.message",
"message": data
}
async_to_sync(channel_layer.send)(channel_name, event)如您所见,我创建了一个函数名: websocket_send_data(data,channel_name),我可以在GendataThread()中调用它,如下所示:
class GendataThread(threading.Thread):
"""new thread
thread for getting data from cluster, and send to front with websocket protocol.
"""
def __init__(self, *args, **kwargs):
super(GendataThread, self).__init__(*args, **kwargs)
self.channels_name = None
def run(self):
while true:
websocker_send_data('1', self.channels_name)在这种情况下,当django项目运行时,我可以从后台向前端发送数据,我连接到url。
ws://127.0.0.1:8000/ws/intime_data在routing.py中设置如下:
websocket_urlpatterns = [
url(r'^ws/intime_data$', consumers.WebsocketConsumer),
] 我可以在前面接收数据,但当它运行几分钟时,事情就出错了:
aioredis.errors.ReplyError: OOM command not allowed when used memory > 'maxmemory'.我认为是因为redis通过保存数据而被填满,但我不想要这些数据,我尝试通过以下方式配置redis.conf:
maxmemory-policy allkeys-lru 但是当使用maxmemory时,仍然会出现错误。有时会出现这样的错误:
channels.exceptions.Channels Full我认为channels正在使用redis作为缓存,但我不知道为什么会出现错误,有人能帮我吗?提前谢谢。
发布于 2021-08-04 05:45:08
将此代码添加到settings.py中
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [(XXX, XXX)],
},
"ROUTING": "XXXXXchannel_routing"
},
}https://stackoverflow.com/questions/53019334
复制相似问题