我正在尝试将 celery 与 django 通道集成,但通道消费者没有按预期工作。消费者功能内的日志记录或打印不会在终端中显示消息。
以下 celery 任务是从 signal.py 调用的
任务.py
from channels.layers import get_channel_layer
@app.task
def send_request_notification():
text = 'You have new cleaning request'
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'companies_received_request', # group name
{
'type': 'send_notification',
'text': text
}
)
print("SENT ---") # can see result of this print
consumers.py
class NotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
logger.info("Connected to websocket")
await self.channel_layer.group_add(
'companies_received_request', self.channel_name
)
await self.accept()
async def disconnect(self):
await self.channel_layer.group_discard(
'companies_received_request', self.channel_name
)
logger.info("Disconnected from websocket")
async def send_notification(self, event):
logger.info("Here in sending notification")
text_message = event['text']
await self.send(text_message)
print("EVENT.TEXT")
print(text_message)
设置.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [('127.0.0.1', 6379)],
},
},
}
我应该在终端中获取打印的输出和消费者函数的日志记录,但是当我从
channel_layer.group_send
任务中调用 celery
方法时,我什么也没得到。 (celery
似乎无法与consumer
建立联系)
Django 的输出在 Docker 容器中运行时会被缓冲。
为了确保输出不被缓冲,请将
PYTHONUNBUFFERED
环境变量设置为非空字符串。
您可以在 Dockerfile 或启动脚本中写入
export PYTHONUNBUFFERED=1
。