我有一个应用程序需要初始化Celery和其他东西(例如数据库).我想有一个包含应用程序配置的.ini文件.这应该在运行时传递给应用程序.
development.init:
[celery]
broker=amqp://localhost/
backend=amqp://localhost/
task.result.expires=3600
[database]
# database config
# ...
Run Code Online (Sandbox Code Playgroud)
celeryconfig.py:
from celery import Celery
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(...) # Pass this from the command line somehow
celery = Celery('myproject.celery',
broker=config.get('celery', 'broker'),
backend=config.get('celery', 'backend'),
include=['myproject.tasks'])
# Optional configuration, see the application user guide.
celery.conf.update(
CELERY_TASK_RESULT_EXPIRES=config.getint('celery', 'task.result.expires')
)
# Initialize database, etc.
if __name__ == '__main__':
celery.start()
Run Code Online (Sandbox Code Playgroud)
为了启动Celery,我打电话给:
celery worker --app=myproject.celeryconfig -l info
Run Code Online (Sandbox Code Playgroud)
无论如何传递配置文件而不做像设置环境变量那样难看的东西?
好吧,我接受了乔丹的建议并使用了一个env变量.这是我在celeryconfig.py中得到的:
celery import Celery
import os
import sys
import ConfigParser
CELERY_CONFIG = 'CELERY_CONFIG'
if not CELERY_CONFIG in os.environ:
sys.stderr.write('Missing env variable "%s"\n\n' % CELERY_CONFIG)
sys.exit(2)
configfile = os.environ['CELERY_CONFIG']
if not os.path.isfile(configfile):
sys.stderr.write('Can\'t read file: "%s"\n\n' % configfile)
sys.exit(2)
config = ConfigParser.RawConfigParser()
config.read(configfile)
celery = Celery('myproject.celery',
broker=config.get('celery', 'broker'),
backend=config.get('celery', 'backend'),
include=['myproject.tasks'])
# Optional configuration, see the application user guide.
celery.conf.update(
CELERY_TASK_RESULT_EXPIRES=config.getint('celery', 'task.result.expires'),
)
if __name__ == '__main__':
celery.start()
Run Code Online (Sandbox Code Playgroud)
启动Celery:
$ export CELERY_CONFIG=development.ini
$ celery worker --app=myproject.celeryconfig -l info
Run Code Online (Sandbox Code Playgroud)
设置环境变量怎么这么难看?您可以使用应用程序的当前版本设置环境变量,也可以根据主机名派生它,或者可以让构建/部署过程覆盖该文件,并在开发时让development.ini 复制到settings.ini在一般位置,在生产环境中,您可以将 production.ini 复制到 settings.ini。
这些选项中的任何一个都很常见。使用配置管理工具(例如 Chef 或 Puppet)将文件放置到位是一个不错的选择。
| 归档时间: |
|
| 查看次数: |
3706 次 |
| 最近记录: |