在项目的目录下创建celery_tasks用于保存celery异步任务。
```broker_url = "redis://127.0.0.1/14"```
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'])
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)
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"})