当尝试运行依赖Django代码的celery任务时,我似乎遇到了22个问题。
芹菜代码
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
from celery import shared_task
from celery import task
from letters.send_write_letter_reminders import send_write_letter_reminders
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings')
app = Celery('app_name')
# 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')
app.conf.timezone = 'Europe/London'
# Load task modules from all registered Django app configs.
app.autodiscover_tasks(settings.INSTALLED_APPS)
@app.task(bind=True, name='send_letter_reminders')
def send_letter_reminders(slug=None):
send_write_letter_reminders(slug=slug)
我遇到的问题是该行
from letters.send_write_letter_reminders import send_write_letter_reminders
有了它我得到:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
应用服务器将无法运行,但是如果没有它,我将得到:
NameError: name 'send_write_letter_reminders' is not defined
很明显,我缺少有关如何同时运行Celery和Django的基本知识,但是我看不到。谁能启发我做错了什么?
更新 我为此提出了一个解决方案,其中涉及将导入移动到celery任务中。我知道这不是最佳做法。也许这可能有助于解释发生了什么。
@app.task(bind=True, name='send_letter_reminders')
def send_letter_reminders(slug=None):
from letters.send_write_letter_reminders import send_write_letter_reminders
send_write_letter_reminders.send_write_letter_reminders(slug=slug)
答案 0 :(得分:0)
从本质上讲,除非执行了import os
from datetime import datetime
now = datetime.now()
time = now.strftime("%H:%M:%S")
pinghost = input("you want to ping: ")
print("Started " + time)
response = os.system("ping -n 6 {}".format(pinghost))
if response == 0:
print('ping complete.')
print("Completed "+time)
else:
print('ping fail.')
行,否则您将无法进行任何django导入或任何依赖django的导入。使用os.environ.setdefault
运行任何内容时,您不必为此担心,原因是manage.py
是manage.py的第一行。从本质上讲,只需将os.environ.setdefault
和django.conf
导入移动到letter
下方,情况应该会更好。根据您所使用的django版本,您可能还需要在设置os.environ.setdefault
后显式调用django.setup()
来完成django设置。