Django celery

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

内容简介: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Ruby元编程

Ruby元编程

[意] Paolo Perrotta / 廖志刚、陈睿杰 / 华中科技大学出版社 / 2012-1-10 / 56.00元

《Ruby元编程》以案例形式循序渐进讲解Ruby对象模型原理和高级应用技巧,堪称动态语言的设计模式。书中讲述的各种Ruby编程模式,完全可以应用于其他动态语言(甚至静态语言)。本书不仅适合Ruby程序员阅读,也适合对动态编程 语言和面向对象编程感兴趣的读者阅读。所有对程序设计理论感兴趣的人都能从中获益。Ruby之父松本行弘作序推荐。一起来看看 《Ruby元编程》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试