运行 如何在 Django App 中使用 Celery 异步执行任务?

How run task asynchronously whith Celery in Django App?

我的settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'FBIsystem',
    'mathfilters',
    #'background_task',
    'celery',
    'widget_tweaks',
)

CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ALWAYS_EAGER = 'False'

我的celery.py

from __future__ import absolute_import
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_try.settings')

from django.conf import settings
from celery import Celery

app = Celery('celery_try',
             backend='amqp',
             broker='amqp://guest@localhost//')

app.config_from_object('django.conf:settings')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)


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

我有一个看法:

def home(request):
    try:
        return render(request, 'app/home.html')
    finally:
        print '1'
        mytask.delay()

我有一个脚本:


from celery import shared_task

@shared_task()
def mytask():
    time.sleep(10)
    print("Test 1234!")

实际上它在 10 秒后呈现 home.html,然后打印测试 1234! 我的目标是渲染 home.html 和 AFTER 10 seconds 运行 mytask()

有什么解决办法吗?

您可以做的最简单的事情就是在 return 渲染 HTML 之前异步调用 mytask mytask。类似于:

def home(request):
    mytask.apply_async()  # delay() is just apply_async() with *args and *kwargs
    return render(request, 'app/home.html')