Skip to main content
 首页 » 编程设计

python之使用 .conf 文件配置 celery

2025年05月04日11jyk

美好的一天。

我建立了一个独立于主项目的项目,名为 myproject-celery。这是一个基于构建的项目,其中包含我项目的异步部分。为了方便起见,我想要一个包含这台机器配置的文件。我知道 celery 提供了 python 配置文件,但我不喜欢这种配置方式。

假设我在名为 myproject.yaml

的 Yaml 配置文件中有一个配置

我要实现的目标:

./bin/celery worker --config /absolute/path/to/project/myproject.yaml --app myproject.celery 

真正的问题是我想指定文件的位置,因为它可以改变。我尝试编写一个自定义加载程序类,但我失败了,因为我什至不知道为什么以及何时调用此类的许多自定义方法(我找到的唯一文档是 http://docs.celeryproject.org/en/latest/reference/celery.loaders.base.html?highlight=loader#id1,这对我没有帮助)。我试图在应用程序模块的导入阶段做一些事情,但我无法将文件路径传递给该模块的代码......我想出的唯一解决方案是使用包含路径的自定义 ENV 参数,但我这样做不明白为什么它不能像我使用的大多数应用程序那样成为启动参数(指金字塔及其 paster serve myproject.ini)

那么问题来了: 我需要做什么才能从我可以通过绝对路径指定的文件设置配置?

编辑: 这个问题没有得到回答,所以我在 celery 的 github 上发布了一个问题。将等待回应。 https://github.com/celery/celery/issues/1100

请您参考如下方法:

查看celery.loaders.base看起来您要覆盖的方法是 read_configuration :

from celery.datastructures import DictAttr 
from celery.loaders.base import BaseLoader 
 
 
class YAMLLoader(BaseLoader): 
    def read_configuration(): 
        # Load YAML file here and return a DictAttr instance