My 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!")
实际上它呈现主页.html 10 秒后,然后打印测试 1234!我的目标是渲染回家.html 10秒后运行mytask((
有什么解决办法吗?
您可以
做的最简单的事情是在返回渲染的 HTML 之前异步调用(就像您已经做的那样(mytask
。像这样:
def home(request):
mytask.apply_async() # delay() is just apply_async() with *args and *kwargs
return render(request, 'app/home.html')