【发布时间】:2019-07-05 12:56:16
【问题描述】:
堆栈:
Python v2.7
Django v1.11
Celery v4.3.0
Gunicorn v19.7.1
Nginx v1.10
当我尝试手动运行 django 服务器和 celery 时,异步任务按预期执行。
当我使用
Gunicorn加上Nginx部署django项目时,问题就出现了。 我尝试使用supervisor运行Celery,但没有帮助。
views.py
def _functionA():
_functionB.delay() #where _functionB is registered async task.
settings.py
# Celery settings
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
celery_init.py
from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cpi_server.settings')
app = Celery('myproject')
# 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()
__init__.py
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from myproject.celery_init import app as celery_app
__all__ = ['celery_app']
gunicorn.service
[Unit]
Description=Gunicorn application server....
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=<myprojectdir>
Environment=PYTHONPATH=<ENV>
ExecStart=<myprojectdir>/env/bin/gunicorn --workers 3 --access-logfile access_gunicorn.log --error-logfile error_gunicorn.log --capture-output --log-level debug --bind unix:<myprojectdir>/myproject.sock <myproject>.wsgi:application
[Install]
WantedBy=multi-user.target
myproject_nginx.conf
server {
listen 8001;
location / {
include proxy_params;
proxy_pass http://unix:<myprojectdir>/myproject.sock;
}
}
celery worker
celery worker -B -l info -A myproject -Q celery,queue1,queue2,queue3 -n beat.%h -c 1
谁能帮我解决以下问题:
为什么当使用 Gunicorn 和 nginx 部署 Django 时,Celery worker 不执行任务,而当手动运行时它能够执行任务,即使用
python manage.py runserver ...运行时。
【问题讨论】:
-
运行 Django 服务器的方式对 celery 执行任务的方式完全没有影响。 celery 的全部意义在于它独立于 django 进程。
-
@DanielRoseman 这就是我想不出手动运行 django 时它运行的原因。我会尝试调试更多让我们看看我能找到什么。
-
代码中
celery应用在哪里初始化? -
@sp1rs 我已经更新了我上面的问题,你可以在
celery_init.py和_init_.py找到详细信息 -
您的
_functionB任务在哪里?
标签: python django nginx celery gunicorn