如何在Django App中与Celery异步运行任务?

时间:2019-07-12 09:18:36

标签: python django celery

我的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,然后打印Test 1234! 我的目标是渲染home.html,然后在10秒钟后运行mytask()

有解决方案吗?

1 个答案:

答案 0 :(得分:1)

最简单的方法是在返回渲染的HTML之前立即异步调用mytask(正如您已经做过的那样)。像这样:

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