python使用celery实现异步任务执行的例子

今天小编就为大家分享一篇python使用celery实现异步任务执行的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
使用celery在django项目中实现异步发送短信

在项目的目录下创建celery_tasks用于保存celery异步任务。

在celery_tasks目录下创建config.py文件,用于保存celery的配置信息

```broker_url = "redis://127.0.0.1/14"```

在celery_tasks目录下创建main.py文件,用于作为celery的启动文件

from celery import Celery
 # 为celery使用django配置文件进行设置
 
import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
  os.environ['DJANGO_SETTINGS_MODULE'] = 'model.settings.dev'
 
 # 创建celery应用
 
app = Celery('model')
 
 #导入celery配置
 
app.config_from_object('celery_tasks.config')
 #自动注册celery任务
app.autodiscover_tasks(['celery_tasks.sms'])

在celery_tasks目录下创建sms目录,用于放置发送短信的异步任务相关代码。

将提供的发送短信的云通讯SDK放到celery_tasks/sms/目录下。

在celery_tasks/sms/目录下创建tasks.py(这个名字是固定的,非常重要,系统将会自动从这个文件中找任务队列)文件,用于保存发送短信的异步任务

import logging
 
from celery_tasks.main import app
from .yuntongxun.sms import CCP
 
logger = logging.getLogger("django")
 
 #验证码短信模板
SMS_CODE_TEMP_ID = 1
 
@app.task(name='send_sms_code')
  def send_sms_code(mobile, code, expires):
 
发送短信验证码
:param mobile: 手机号
:param code: 验证码
:param expires: 有效期
:return: None
 
 
try:
  ccp = CCP()
  result = ccp.send_template_sms(mobile, [code, expires], SMS_CODE_TEMP_ID)
except Exception as e:
  logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
else:
  if result == 0:
    logger.info("发送验证码短信[正常][ mobile: %s ]" % mobile)
  else:
    logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)

在verifications/views.py中改写SMSCodeView视图,使用celery异步任务发送短信

from celery_tasks.sms import tasks as sms_tasks
 
class SMSCodeView(GenericAPIView):
  ...
    # 发送短信验证码 这是将时间转化为分钟,constants.SMS_CODE_REDIS_EXPIRES 是常量
    sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
 
    sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)
 
    return Response({"message": "OK"})

以上这篇python使用celery实现异步任务执行的例子就是小编分享给大家的全部内容了

推荐我们的python学习基地,点击进入,看老程序是如何学习的!从基础的python脚本、爬虫、django、数据挖掘等编程技术,工作经验,还有前辈精心为学习python的小伙伴整理零基础到项目实战的资料,!每天都有程序员定时讲解Python技术,分享一些学习的方法和需要留意的小细节

发布了41 篇原创文章 · 获赞 39 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/haoxun07/article/details/104544919