我坚持使用 settings.py 内 .env 文件中的配置变量来 celery.py。
当我对CELERY_BROKER_URL = 'redis://localhost'
进行硬编码时,一切正常,但是,当我使用CELERY_BROKER_URL= os.environ.get('REDIS_URL')
时,REDIS_URL没有被接管,我收到错误。
celery.py:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ['DJANGO_SETTINGS_MODULE'] = 'xlink.settings'
app = Celery('xlink')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
.env:
REDIS_URL = 'redis://localhost'
REDIS_PASSWORD = 'yow'
REDIS_HOST = 'localhost'
settings.py 版本 1 不起作用:
CELERY_BROKER_URL= os.environ.get('REDIS_URL')
CELERY_RESULT_BACKEND= os.environ.get('REDIS_URL')
错误版本 1(尝试接管默认的 Redis 设置,如给出的说明所示(:
[2017-08-26 10:57:09,253: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused.
Trying again in 2.00 seconds...
settings.py 版本 2 不起作用:
CELERY_BROKER_URL = 'redis://:{}@{}:6379/0'.format(
os.environ.get('REDIS_PASSWORD'),
os.environ.get('REDIS_HOST'))
错误版本 2(显然没有接管 .env 变量(:
[2017-08-26 11:11:03,419: ERROR/MainProcess] consumer: Cannot connect to redis://:**@none:6379/0: Error 8 connecting to none:6379. nodename nor servname provided, or not known..
Trying again in 2.00 seconds...
工作 settings.py:
CELERY_BROKER_URL= 'redis://localhost'
CELERY_RESULT_BACKEND= 'redis://localhost'
tasks.py:
import celery
from celery import shared_task
@shared_task
def add(x, y):
return x + y
我犯的最大错误是关于使用以下代码将芹菜工人与命令行分开运行:
celery -A xlink worker -l info
将这行代码添加到 procfile 并使用 heroku 命令运行解决了这个问题。
轮廓:
web: gunicorn xlink.wsgi --threads 4 --log-level debug
worker: celery -A xlink worker -l info
命令使其运行:
heroku local worker
如果要在一个终端窗口中同时运行工作线程和 Web 应用程序,只需执行heroku local
,两者在一个终端窗口中同时启动。
感谢罗斯曼@Daniel提示