如何 运行 在 django 中使用 celery 执行任务并将结果保存在 django 数据库中?

How to run a task with celery in django and save result in django database?

我制作了一个抓取器来从网页上抓取一些链接,并希望每 1 小时 运行 这个抓取器驻留在 django 应用程序中,但是 django 不可能每隔 运行 一个抓取器1 小时,因为 django 视图取决于请求响应对象。为了解决这个问题,我决定使用一个名为 celery 的 python 库,根据我编写的文档 celery.py 和 tasks.py 文件

通过django的项目结构是这样的

newsportal
 - newsportal
    -settings.py 
    -celery.py
    __init__.py
 - news
    -tasks.py
    -views.py 
    -models.py

celery.py 有以下代码

from __future__ import absolute_import

import os

from celery import Celery

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

from django.conf import settings  # noqa

app = Celery('newsportal')

# 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.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

__init__.py文件有如下代码行

from __future__ import absolute_import

# 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  # noqa

while as tasks.py 有以下代码行

from __future__ import absolute_import
from celery import shared_task
from crawler import crawler
from .models import News

@shared_task
def news():
    '''
    scrape all links
    '''
    news = [] #store dict object
    allnews.append(crawler()) 
    for news_dict in allnews:
        for news, url  in news_dict.items():
            #Save all the scrape news in database
            News.objects.create(title=news, url=url, source=source)

我想做的是每1小时运行上面的news()函数并将结果保存到数据库中。

我想将任务的结果保存到django数据库中,我该如何实现。

根据 celery 文档,要保存工作人员给出的结果,我们需要安装 django-celery==3.1.17,因为我已经安装了,并进行迁移。

根据 celery 文档,对于 celery 中的数据库后端,我们应该放置

app.conf.update(
    CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
)



line of code on settings.py file, on putting this of code in `settings.py` file I got the error of

settings.py", line 141, in <module>
    app.conf.update(
NameError: name 'app' is not defined

因为我已经将以下代码行导入并放入 settings.py 文件中,如下所示

from __future__ import absolute_import
BROKER_URL = 'redis://localhost'

我想做的主要事情是,

  1. 运行以上爬虫每1小时一次并保存结果 名为新闻的数据库中的爬虫 我如何使用芹菜完成此操作,还是我遗漏了什么?

是否有任何其他替代方法来完成此任务

如果您想在 celery.py 中添加该配置,我相信您会在 app.conf.update(...) 中使用 app.conf.update(...)

您在 celery.py 中的 app.config_from_object('django.conf:settings') 调用表明您正在从 settings.py 文件加载配置设置。

所以您应该可以将 CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend' 放在 settings.py 文件的末尾。

这应该可以防止您遇到该错误。

我知道这有点晚了,但是我强烈推荐找到的 Django Celery 结果包 here

安装很直接,安装包是Celery自己推荐的。只需 return 您任务的一些输出,它将存储在数据库中,并可在 Django 管理员下访问。