【发布时间】:2018-05-30 05:20:34
【问题描述】:
在 django 应用程序中,我正在运行异步任务,并希望向用户显示进度、错误等。如果有错误,用户应该被重定向到需要额外输入或一些操作来解决问题的页面。从 celery 工作回到前端的最佳沟通方式是什么?
这是伪代码的基本结构:
# views.py
from tasks import run_task
def view_task():
run_task.delay()
return render(request, 'template.html')
# tasks.py
from compute_module import compute_fct
@shared_task
def run_task():
result = compute_fct()
# how to catch status update messages from compute_module while compute_fct is running??
if result == 'error':
handle_error()
else:
handle_succes()
# compute_module
import pandas as pd
def compute_fct():
# send message: status = loading file
df = pd.read_csv('test.csv')
# send message: status = computing
val = df['col'].mean()
if val is None:
return {'status':'error'}
else:
return {'status':'success','val':val}
我最想要的:
-
compute_module.py模块使用 python 原生记录器。通过职责分离,我希望尽可能保持日志的通用性并使用标准的 python/django 记录器。但它们似乎并非旨在将消息发送到前端。 - celery 任务以某种方式处理日志,而不是在标准输出上显示它们,而是将它们重定向到推送器
- 前端js显示并处理消息
芹菜工人和前端之间可能有标准的通信方式,我不知道。这种情况必须经常发生,我很惊讶它如此难以实施。在某种程度上,应该为此设计 rabbitmq 消息队列或 aws sns。以下是我查看过的资源,但感觉它们中的任何一个都不是很好,但也许我只是感到困惑。
日志:这似乎更多是关于在服务器端登录,而不是向用户发送消息
- http://docs.celeryproject.org/en/latest/userguide/tasks.html#logging
- https://docs.djangoproject.com/en/2.0/topics/logging/
- http://oddbird.net/2017/04/17/async-notifications/
- https://www.google.com/search?q=celery+worker+send+message+to+front+end
Celery cam 似乎是关于管理员监控任务,而不是向用户发送消息
我喜欢推送器,但我不想让compute_module.py 处理它。例如,我不希望在compute_module.py 中进行任何 pusher.com 集成。猜猜我可以传递一个已经实例化的推送器对象,这样模块就可以推送消息,但我还是希望它是通用的
【问题讨论】:
-
在您的情况下,进度报告的位置是什么?您运行一项任务,它已完成或出错。如果您运行分解为子任务的任务,您可以使用网络工作者将每个子任务的最终输出推送回客户端吗?我也不是真的 感觉 python 日志记录作为用户反馈机制 - 我怀疑获得 nice 输出,尤其是 html 将比它的价值更麻烦。
标签: python django logging celery pusher