简体   繁体   English

Django:如何忽略 Celery 的任务?

[英]Django: How to ignore tasks with Celery?

Without changing the code itself, Is there a way to ignore tasks in Celery?在不更改代码本身的情况下,有没有办法忽略 Celery 中的任务?

For example, when using Django mails, there is a Dummy Backend setting.例如,当使用 Django 邮件时,有一个Dummy Backend设置。 This is perfect since it allows me, from a .env file to deactivate mail sending in some environments (like testing, or staging).这是完美的,因为它允许我从.env文件停用某些环境(如测试或暂存)中的邮件发送。 The code itself that handles mail sending is not changed with if statements or decorators.处理邮件发送的代码本身不会因if语句或装饰器而改变。

For celery tasks, I know I could do it in code using mocks or decorators, but I'd like to do it in a clean way that is 12factors compliant, like with Django mails.对于 celery 任务,我知道我可以使用模拟或装饰器在代码中完成,但我想以一种符合 12 因素的干净方式来完成,就像 Django 邮件一样。 Any idea?任何的想法?

EDIT to explain why I want to do this:编辑以解释我为什么要这样做:

One of the main motivation behind this, is that it creates coupling between Django web server and Celery tasks.这背后的主要动机之一是它在 Django web 服务器和 Celery 任务之间创建耦合。 For example, when running unit tests, if the broker server (Redis for me) is not running, then if delay() method is called, it freezes forever, because there is no timeout when Celery tries to send a task to Redis. From an architecture view, this is very bad.例如,在运行单元测试时,如果代理服务器(对我来说是 Redis)没有运行,那么如果调用delay()方法,它将永远冻结,因为当 Celery 尝试向 Redis 发送任务时没有超时。从架构的角度来看,这是非常糟糕的。 I'd like my unit tests can run properly without the requirement to run a Celery broker!我希望我的单元测试能够正常运行而无需运行 Celery 代理!

Thanks!谢谢!

As far as the coupling is concerned, your Django application would still be tied to celery if you use a dummy backend.就耦合而言,如果您使用虚拟后端,您的 Django 应用程序仍将绑定到 celery。 Just your tasks won't execute.只是您的任务不会执行。 Maybe this is acceptable in your case but in my opinion, it can cause some problems.也许这在您的情况下是可以接受的,但在我看来,它可能会导致一些问题。 For example, if the piece of code you are trying to test, submits a task to celery, and in a later part, tries to retrieve the result for that task, it will fail.例如,如果您尝试测试的代码片段向 celery 提交了一个任务,而在稍后的部分中,尝试检索该任务的结果,它将失败。 Because the dummy backend will never execute the task.因为虚拟后端永远不会执行任务。

For unit testing, as you mentioned in your question, you can use the task_always_eager setting.对于单元测试,正如您在问题中提到的,您可以使用task_always_eager设置。 If you turn it on, your Django app will no longer depend upon a running worker.如果你打开它,你的 Django 应用将不再依赖于正在运行的 worker。 It will execute tasks in the same thread in a synchronous fashion and return the result.它将以同步方式在同一个线程中执行任务并返回结果。

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

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