如何解决django 信号与 heroku 上的芹菜任务
我正在尝试通过 heroku 爱好计划中的 django 信号触发 celery 任务。到目前为止,在线示例和教程使我获得了以下代码,但是在运行时,它使任务保持同步模式,并且从 redis 中发生工作超时。
requirements.txt
...
celery==5.0.5
redis==3.5.3
./myproj/init.py
from __future__ import absolute_import
from .celery import app as celery_app
__all__ = ('celery_app',)
./myproj/celery.py
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE',"myproj.settings.heroku_settings")
app = Celery("myproj")
app.config_from_object('django.conf:settings',namespace = 'CELERY')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
#
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
./myproj/settings/heroku_settings.py
...
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_BROKER_URL = str(env('REDIS_URL')) # from heroku config vars (heroku redis free plan)
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
...
./myproj/signals.py
...
@receiver(post_save,sender=Resume)
def update_pdf_from_resume(sender,instance,created,**kwargs):
""" Create a new pdf if resume is updated."""
# disconnect signals to avoid chain reactions
post_save.disconnect(update_pdf_from_resume,sender=Resume)
# async generate resume
generate_one_page_resume.delay(instance_id = instance.pk)
# reconnect signals
post_save.connect(update_pdf_from_resume,sender=Resume)
** ./myapp/tasks.py**
from celery import shared_task
...
@shared_task
def generate_one_page_resume(instance_id : int):
""" Generates a one pager resume through signals asynchronously."""
# get resume model
resume = Resume.objects.get(id = instance_id)
# do something to another model entry
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。