Django celery

栏目: Python · 发布时间: 7年前

内容简介:python3.6+Repo:https://github.com/Cooolis/CooolisGather首先创建一个Django项目,再创建一个app。

0x01 环境

python3.6+

Repo:https://github.com/Cooolis/CooolisGather

0x02 主要库安装

pip install celery==3.1.26.post2
pip install celery-with-redis==3.0
pip install Django
pip install redis==2.10.6

首先创建一个Django项目,再创建一个app。

django-admin startproject CooolisGather
django-admin startapp gather

修改Settings添加BROKER:

BROKER_URL = 'redis://127.0.0.1:6379/0'

Django celery

0x03 配置celery

在CooolisGather目录文件夹下新建一个 celery.py 文件:

from __future__ import absolute_import

import os
import django

from celery import Celery
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CooolisGather.settings')
django.setup()

app = Celery('CooolisGather')

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

0x04 配置tasks

gather 目录下新建 tasks.py

from CooolisGather.celery import app
from .tasks_handle.port_scan_handle import PortScanTask


@app.task(base=PortScanTask)
def hello_world():
    print('Hello World')

第一行主要是为了让 gather 找到 celery 的配置。

tasks_handle 主要是为了在触发 tasks 时能有其他功能,例如下发了一个端口扫描任务,任务触发了 hello_world ,那么在执行完毕需要将扫描结果写入数据库等操作,这种需求下就可以让 @app.task 继承 base=PortScanTask

0x05 调用tasks

更改 gather/views.py

from django.http import HttpResponse
from .tasks import hello_world

def index(request):
    hello_world.delay()
    return HttpResponse('Hello')

其中 delay() 方法主要用于异步执行。

0x06 遇到的坑

1.redis库版本不能太高 2.使用pycharm进行调试celery时,启动celery它默认是调用的系统库,而不是env

0x07 启动项目

~# celery worker -A CooolisGather -l debug
~# python manage.py runserver 8080

Django celery

访问主页将会调用 tasks.hello_word ,而 tasks.hello_word 有继承于 PortScanTask :

from celery import Task


class PortScanTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        print("Done")
        return super(PortScanTask, self).on_success(retval, task_id, args, kwargs)

Django celery

tasks.hello_word 在执行完毕任务后,会自动调用 on_success


以上所述就是小编给大家介绍的《Django celery》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

数据结构与算法

数据结构与算法

卓滋德克 / 陈曙晖 / 清华大学出版社 / 2003-4-1 / 69.00

本书是一本介绍数据结构与算法的优秀书籍。 本书系统介绍了C++面向对象程序设计、算法复杂度、链表、栈、队列、递归、树、图、排序和查找算法、散列技术、数据压缩算法、内存管理等内容;尤其对递归算法进行了深入剖析。在附录中详细介绍了大O符号与标准模板库:在大多数章中提供了相应的实例分析和程序设计作业。 本书适合作为计算机软件专业或其他相关专业的教科书。对于需要参加计算机考试,......一起来看看 《数据结构与算法》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

MD5 加密
MD5 加密

MD5 加密工具