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

查看所有标签

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

Python机器学习基础教程

Python机器学习基础教程

[德]安德里亚斯·穆勒、[美]莎拉·吉多 / 张亮 / 人民邮电出版社 / 2018-1 / 79.00元

本书是机器学习入门书,以Python语言介绍。主要内容包括:机器学习的基本概念及其应用;实践中最常用的机器学习算法以及这些算法的优缺点;在机器学习中待处理数据的呈现方式的重要性,以及应重点关注数据的哪些方面;模型评估和调参的高级方法,重点讲解交叉验证和网格搜索;管道的概念;如何将前面各章的方法应用到文本数据上,还介绍了一些文本特有的处理方法。一起来看看 《Python机器学习基础教程》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

SHA 加密
SHA 加密

SHA 加密工具