BBS论坛(三十三)
2025年01月15日 02:41:40

LIKE.TG 成立于2020年,总部位于马来西亚,是首家汇集全球互联网产品,提供一站式软件产品解决方案的综合性品牌。唯一官方网站:www.like.tg
33.celery实现邮件异步发送
(1)task.py
pip install celery redis
from celery import Celery
from flask import Flask
from flask_mail import Message
from exts import mail,alidayu
import config
app=Flask(__name__)
app.config.from_object(config)
mail.init_app(app)
alidayu.init_app(app)
# 运行本文件:
# 在windows操作系统上:
# celery -A tasks.celery worker --pool=solo --loglevel=info
# 在linux操作系统上:
# celery -A tasks.celery worker --loglevel=info
def make_celery(app):
celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(app)
@celery.task
def send_mail(subject,recipients,body):
message = Message(subject=subject,recipients=recipients,body=body)
mail.send(message)
# @celery.task
# def send_sms_captcha(telephone,captcha):
# alidayu.send_sms(telephone,code=captcha)
(2)config.py
# celery的配置
CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/0"
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
(3)cms/views.py
@bp.route('/email_captcha/')
def email_captcha():
#获取要修改的邮箱
email = request.args.get('email')
if not email:
return restful.params_error('请输入要修改的邮箱')
#得到大小写字母的列表
source = list(string.ascii_letters)
#得到大小写字母的列表 + 0到9的数字字符串
source.extend(map(lambda x: str(x), range(0, 10)))
# 随机取六位作为验证码
captcha = "".join(random.sample(source, 6))
#给这个邮箱发送邮件验证码
# message = Message(subject='derek论坛密码修改邮件发送', recipients=[email,], body='你的验证码是:%s'%captcha)
# try:
# mail.send(message)
# except:
# return restful.server_error()
#celery异步发送邮件
send_mail.delay('derek论坛密码修改邮件发送', [email], '你的验证码是:%s' % captcha)
#把邮箱和验证码保存到memcached中
zlcache.set(email,captcha)
return restful.success()

现在关注【LIKE.TG出海指南频道】、【LIKE.TG大客户服务频道】,即可免费领取【WhatsApp、LINE、Telegram、Twitter、ZALO云控】等获客工具试用、【住宅IP、号段筛选】等免费资源,机会难得,快来解锁更多资源,助力您的业务飞速成长!点击【联系客服】
本文由LIKE.TG编辑部转载自互联网并编辑,如有侵权影响,请联系官方客服,将为您妥善处理。
This article is republished from public internet and edited by the LIKE.TG editorial department. If there is any infringement, please contact our official customer service for proper handling.
Server deployment全球论坛人工智能论坛全球峰会发展论坛战略论坛开放论坛程序员论坛互联网峰会科技峰会