将Celery任务保存在DB-Django中

时间:2014-02-17 08:22:56

标签: python django celery djcelery

我指的是Django Celery文件。

我在celery.py创建了proj/proj,就像文件所说的那样。然后包括__init__.py

celery.py

from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
app = Celery('proj')
app.conf.update(
    CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
)
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

__初始化__。PY

from __future__ import absolute_import
from .celery import app as celery_app

我安装了pip install django-celery,然后迁移了python manage.py migrate djcelery 它在我的数据库中制作了一些表格。

tasks.py

from __future__ import absolute_import
from celery import shared_task
import requests
import json

@shared_task
def post_notification(data,url):
    headers = {'content-type': 'application/json'}
    requests.post(url, data=json.dumps(data), headers=headers)

之后我在视图中调用了我的任务

task = post_notification.delay(data,url)
print task.id #it prints an id
print task.status # prints PENDING

但是没有任何内容记录到我的任何表中。

我已经在SO上发现了我的帖子,Thread1Thread2以及在这些帖子上给出的更多内容,但没有任何反应。

它为我提供了ID&任务的状态,但如何将任务保存在数据库中?通常它应该登录celery_taskmeta,但那里什么都没有。

虽然任务已执行但我也想将任务保存在DB中。我该怎么做?有什么我想念的吗?

2 个答案:

答案 0 :(得分:0)

在celery.py

中试试
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
from celery.schedules import crontab

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.dev_settings')

app = Celery('app_name')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
app.conf.CELERY_TIMEZONE = 'UTC'
app.conf.update(
    CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
)

答案 1 :(得分:0)

settings.py文件

中添加以下内容
BROKER_URL = 'amqp://guest:guest@localhost//'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

启动工人。