【问题标题】:Celery task (.delay()) causes Django to freeze if I'm using Gunicorn or uWsgi如果我使用 Gunicorn 或 uWsgi,Celery 任务 (.delay()) 会导致 Django 冻结
【发布时间】:2021-12-20 01:37:34
【问题描述】:

如果我在使用 Gunicorn 或 uWsgi 时将 celery 与 Django 一起使用(通过调用 .delay()),它会导致它冻结并最终超时。我猜它在尝试向代理发送任务时会卡住。这发生在开发者服务器和生产服务器上,两者都运行 Ubuntu 20.04。

使用内置的开发者服务器 python3 manage.py 运行服务器 工作没有任何问题。

删除 .delay() 也会使其自动工作。

示例任务:

@shared_task
def SayHello():
    print('Hello!')

settings.py 中的 Celery 配置:

CELERY_BROKER_URL = 'redis://:password@ip:6379'
CELERY_RESULT_BACKEND = 'redis://:password@ip:6379'
CELERY_ACCEPT_CONTENt = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER ='json'

初始化.py:

from __future__ import absolute_import, unicode_literals
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)

celery.py(在带有 settings.py 的项目文件夹中):

import os

from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings')

app = Celery('djangoProject')

# 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 apps.
app.autodiscover_tasks()

celery = Celery(__name__)
celery.config_from_object(__name__)

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

【问题讨论】:

    标签: django django-rest-framework redis celery gunicorn


    【解决方案1】:

    拔了一天头发后,我想我找到了。

    我从 celery.py 文件中删除了以下几行:

    celery = Celery(__name__)
    celery.config_from_object(__name__)
    

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 2020-12-08
      • 2019-11-24
      • 2020-12-14
      • 2021-02-25
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      相关资源
      最近更新 更多