在與項目同名的目錄下建立celery.py文件,特別注意:項目同名的目錄下php
修改兩處內容node
import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('pro') # 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() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}')
# 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文件中添加配置python
# Celery配置 CELERY_BROKER_URL = env("CELERY_BROKER_URL") CELERY_RESULT_BACKEND = env("CELERY_RESULT_BACKEND") CELERY_ACCEPT_CONTENT = ["json", "msgpack"] CELERY_TASK_SERIALIZER = "json" CELERY_TIMEZONE = "Asia/Shanghai" CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60
from rest_framework.response import Response from rest_framework.generics import GenericAPIView from time import sleep from celery import shared_task class TestView3(GenericAPIView): @classmethod @shared_task def sleep(self, duration): sleep(duration) return Response("成功", status=200)
### views.py from .tasks import TestView3 class TestView1(GenericAPIView): def get(self, request): TestView3.sleep(10) return Response("celery實驗成功") test_view_1 = TestView1.as_view() ### urls.py from django.urls import path from .views import ( test_view_1 ) urlpatterns = [ path('celery/', test_view_1, name="test1") ]
celery@AppledeMacBook-Air.local v5.0.3 (singularity) Darwin-20.1.0-x86_64-i386-64bit 2020-12-05 20:52:17 [config] .> app: drf_email_project:0x7f84a0c4ad68 .> transport: redis://127.0.0.1:6379/1%20 .> results: redis://127.0.0.1:6379/2 .> concurrency: 4 (prefork) .> task events: OFF (enable -E to monitor tasks in this worker) [queues] .> celery exchange=celery(direct) key=celery [tasks] . drf_email_project.celery.debug_task . users.tasks.sleep [2020-12-05 20:52:18,166: INFO/MainProcess] Connected to redis://127.0.0.1:6379/1%20 [2020-12-05 20:52:18,179: INFO/MainProcess] mingle: searching for neighbors [2020-12-05 20:52:19,212: INFO/MainProcess] mingle: all alone [2020-12-05 20:52:19,248: WARNING/MainProcess] /Users/apple/drf-email/lib/python3.7/site-packages/celery/fixups/django.py:204: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! leak, never use this setting in production environments!''') [2020-12-05 20:52:19,249: INFO/MainProcess] celery@AppledeMacBook-Air.local ready.