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']
在settings.py同级目录新建celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dc_test.settings')
app = Celery('dc_test')
# Using a string here means the worker don'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')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)defdebug_task(self):
print('Request: {0!r}'.format(self.request))
在APP目录下新建tasks.py
from __future__ import absolute_import, unicode_literals
from celery import shared_task
@shared_taskdefhello_world():with open("output.txt", "a") as f:
f.write("hello world")
f.write("\n")