内容简介: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'
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
访问主页将会调用 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)
tasks.hello_word 在执行完毕任务后,会自动调用 on_success 。
以上所述就是小编给大家介绍的《Django celery》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Django celery
- Django 中使用 Celery
- Django - Celery异步任务队列
- Django&Celery是怎么玩的?
- Django与Celery实现异步对列
- 配置Django的Celery异步之路踩坑
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Persuasive Technology
B.J. Fogg / Morgan Kaufmann / 2002-12 / USD 39.95
Can computers change what you think and do? Can they motivate you to stop smoking, persuade you to buy insurance, or convince you to join the Army? "Yes, they can," says Dr. B.J. Fogg, directo......一起来看看 《Persuasive Technology》 这本书的介绍吧!