celery的基础用法可以参考之前转载的文章:
https://blog.csdn.net/ATOOHOO/article/details/88976521
celery 按照固定的套路是可以编写出一下的程序的,中间人使用的是Redis,其他的RabbitMQ等也是可以,可以参考官方文档:
http://docs.celeryproject.org/en/latest/getting-started/brokers/index.html#broker-overview
from django.core.mail import send_mail
from django.conf import settings
from celery import Celery
import time
# django环境的初始化,在任务处理者worker一端加以下几句
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings')
django.setup()
# 创建一个Celery类的实例对象,celery_tasks.tasks可以随便取一个名字,但是一般取有意义的名字
app = Celery('celery_tasks.tasks', broker='redis://127.0.0.1:6379/8')
# 定义任务函数
@app.task
def send_register_active_email(to_email, username, token):
"""发送激活邮件"""
# 组织邮件信息
subject = '天天生鲜欢迎信息'
message = ''
sender = settings.EMAIL_PROM # 发送人
receiver = [to_email]
html_message = '%s, 欢迎您成为天天生鲜注册会员
请点击下面链接激活您的账户
http://127.0.0.1:8000/user/active/%s' % (username, token, token)
send_mail(subject, message, sender, receiver, html_message=html_message)
# time.sleep(5)
celery中的一个很重要的角色是worker,集合Django实用的话,会用到Django中的一些配置,所以需要引入配置信息:
# django环境的初始化,在任务处理者worker一端加以下几句
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings')
django.setup()
否则的话会报出下面的错误信息,说是没能找到Django的配置信息:
[2019-08-20 18:10:45,039: INFO/MainProcess] Received task: celery_tasks.tasks.send_register_active_email[92d688f5-a42e-441a-8676-08eb2f480c8b]
[2019-08-20 18:10:45,148: ERROR/ForkPoolWorker-2] Task celery_tasks.tasks.send_register_active_email[92d688f5-a42e-441a-8676-08eb2f480c8b] raised unexpected: ImproperlyConfigured('Requested setting EMAIL_PROM, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.',)
Traceback (most recent call last):
File "/home/toohoo/.local/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task
R = retval = fun(*args, **kwargs)
File "/home/toohoo/.local/lib/python3.6/site-packages/celery/app/trace.py", line 648, in __protected_call__
return self.run(*args, **kwargs)
File "/home/toohoo/PycharmProjects/mydailyfresh/celery_tasks/tasks.py", line 22, in send_register_active_email
sender = settings.EMAIL_PROM # 发送人
File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_PROM, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
在主要的view里面调用队列发送邮件:
# 获取username
username = ...
# 获取email
email = ...
# 定义好token
token = ...
# 开始调用异步队列发送邮件celery:异步执行任务
send_register_active_email.delay(email, username, token)
注意: 不要漏掉使用delay()函数,否则如果使用send_register_active_email(email, username, token)
的话依然是使用Django内置的邮件模块帮我们发的邮件!
启动成功和发送成功之后的信息:
(venv) toohoo@ubuntu:~/PycharmProjects/mydailyfresh$ celery -A celery_tasks.tasks worker -l info
-------------- celery@ubuntu v4.3.0 (rhubarb)
---- **** -----
--- * *** * -- Linux-4.15.0-58-generic-x86_64-with-Ubuntu-18.04-bionic 2019-08-20 18:42:53
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: celery_tasks.tasks:0x7febbecf5198
- ** ---------- .> transport: redis://127.0.0.1:6379/8
- ** ---------- .> results: disabled://
- *** --- * --- .> concurrency: 2 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. celery_tasks.tasks.send_register_active_email
[2019-08-20 18:42:53,989: INFO/MainProcess] Connected to redis://127.0.0.1:6379/8
[2019-08-20 18:42:54,002: INFO/MainProcess] mingle: searching for neighbors
[2019-08-20 18:42:55,028: INFO/MainProcess] mingle: all alone
[2019-08-20 18:42:55,046: WARNING/MainProcess] /home/toohoo/PycharmProjects/mydailyfresh/venv/lib/python3.6/site-packages/celery/fixups/django.py:202: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments!
warnings.warn('Using settings.DEBUG leads to a memory leak, never '
[2019-08-20 18:42:55,046: INFO/MainProcess] celery@ubuntu ready.
[2019-08-20 18:44:00,183: INFO/MainProcess] Received task: celery_tasks.tasks.send_register_active_email[c3c4d266-838e-4955-ac39-f0ca38cf0463]
[2019-08-20 18:44:06,714: INFO/ForkPoolWorker-2] Task celery_tasks.tasks.send_register_active_email[c3c4d266-838e-4955-ac39-f0ca38cf0463] succeeded in 6.527261982992059s: None
项目代码和地址为:
https://github.com/too-hoo/mydailyfresh