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

查看所有标签

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

新经济,新规则

新经济,新规则

[美]Kevin Kelly / 刘仲涛 / 译言·东西文库/电子工业出版社 / 2014-7 / CNY 45.00

近年来,互联网持续震动着全世界各个行业以至于整个经济规则……在中国,以小米为代表的各类“互联网思维”轰轰烈烈地颠覆着各个行业……而这一切的一切,凯文凯利早就通过这本小书轻松写定。《新规则,新经济》一书介绍互联网时代,互联网影响下的经济运行的十个新游戏规则。一起来看看 《新经济,新规则》 这本书的介绍吧!

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具