redis-django

安装环境

pip install celery 
pip install redis

配置Celery

异步执行代码

tesks.py

from django.core.mail import send_mail
from django.conf import settings
from django.template import loader, RequestContext
from celery import Celery, platforms


# 初始化一个Celery类的实例对象
app = Celery('celery_tasks.tasks')

# 配置应用
app.conf.update(
    # 配置broker, 这里我们用redis作为broker
    BROKER_URL='redis://127.0.0.1:6379/1',
)

# 设置app自动加载任务
# 从已经安装的app中查找任务
app.autodiscover_tasks(settings.INSTALLED_APPS)


# 调用celery发邮件
@app.task
def send_register_active_email(to_email, username, token):
    '''发送激活邮件'''
    subject = '天天生鲜欢迎信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    html_message = '<h1>%s, 欢迎您成为天天生鲜注册会员</h1>请点击下面链接激活您的账户<br/><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>' % (username, token, token)

    send_mail(subject, message, sender, receiver, html_message=html_message)

views.py

from celery_tasks.tasks import send_register_active_email


# 将send_register_active_email任务加入到celery队列中,如果my_task函数有参数,可通过delay()传递
send_register_active_email.delay(email, username, token)

记住:当有多个装饰器的时候,app.task一定要在最外层;

 

启动服务

celery -A tasks worker -Q queue -l info



存储任务结果

此处需要用到额外包django_celery_results, 先安装包:

pip install django-celery-results

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'demo',
    'django_celery_results',  # 注意此处应用名为下划线
]

回到celery_demo/celery.py模块中,增加配置信息如下:

from django.core.mail import send_mail
from django.conf import settings
from django.template import loader, RequestContext
from celery import Celery, platforms


# 初始化一个Celery类的实例对象
app = Celery('celery_tasks.tasks')

# 配置应用
app.conf.update(
    # 配置broker, 这里我们用redis作为broker
    BROKER_URL='redis://127.0.0.1:6379/1',
    # 使用项目数据库存储任务执行结果
    CELERY_RESULT_BACKEND='django-db',
)

# 设置app自动加载任务
# 从已经安装的app中查找任务
app.autodiscover_tasks(settings.INSTALLED_APPS)


# 调用celery发邮件
@app.task
def send_register_active_email(to_email, username, token):
    '''发送激活邮件'''
    subject = '天天生鲜欢迎信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    html_message = '<h1>%s, 欢迎您成为天天生鲜注册会员</h1>请点击下面链接激活您的账户<br/><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>' % (username, token, token)

    send_mail(subject, message, sender, receiver, html_message=html_message)

创建django_celery_results应用所需数据库表, 执行迁移文件:

python manage.py migrate django_celery_results


定时任务

如果我们想某日某时执行某个任务,或者每隔一段时间执行某个任务,也可以使用celery来完成

1.安装

pip install django-celery
pip install django-redis==4.12.1
pip install celery==4.4.0
pip install django-celery-beat==2.1.0
pip install redis==3.5.3
上一篇:Django-celery-redis异步发邮件


下一篇:Celery 进阶使用