简体   繁体   English

使用芹菜作为模型层

[英]Use celery as the model layer

The requirement 要求

I received an unusual requirement: must use celery for communication with the database layer. 我收到了一个不寻常的要求:必须使用celery与数据库层进行通信。

Application is using Flask and MongoDB on the backend and Angular on the frontend. 应用程序在后端使用Flask和MongoDB,在前端使用Angular。

The sponsor believes that I can fire a task, let one of the workers move data in/out of Mongo and get the results back. 发起人认为我可以执行任务,让其中一名工人将数据移入/移出Mongo并取回结果。

My research so far 到目前为止我的研究

As far as I know, if I call a celery task synchronously (using __call__ or apply ), the task is executed locally instead of being sent to the database; 据我所知,如果我同步调用celery任务(使用__call__apply ),则该任务将在本地执行,而不是发送到数据库; if I call it asynchronously, I must block on the Flask side and keep polling the task queue until I get results or an error back. 如果我异步调用它,则必须在Flask一侧阻塞并继续轮询任务队列,直到得到结果或返回错误为止。

Another approach would be modifying the REST API to be make asynchronous calls (return the task ID immediately and keep polling for results on the client side. Personally I abhor the idea, this looks silly for tasks in the millisecond range like basic CRUD operations. 另一种方法是将REST API修改为进行异步调用(立即返回任务ID,并继续在客户端轮询结果。我个人不赞成这种想法,对于毫秒级的任务(如基本CRUD操作)来说,这看起来很愚蠢。

Question

Is there an elegant way to wrap task.delay in order to make it look like a synchronous call and still have the task executed by one of the workers? 是否有一种精美的方法来包装task.delay以使其看起来像同步调用,并且仍由其中一个工作人员执行任务?

Yes, there is - don't know how I missed AsyncResult.get in the docs: 是的,有-不知道我怎么在文档中错过了AsyncResult.get

AsyncResult.get(timeout=None, propagate=True, interval=0.5)

Wait until task is ready, and return its result. 等待任务准备就绪,然后返回其结果。

So you just call the task like this: 因此,您只需这样调用任务:

task.delay(args).get(timeout=1)

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

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