- 在apps下使用命令创建子应用
python ../../manage.py startapp verifications
- 注册
# INSTALLED_APPS 中添加 INSTALLED_APPS = [ ... 'verifications.apps.VerificationsConfig' # 验证模块 ]
- 定义路由在总路由(项目目录下的urls.py添加路由)
urlpatterns = [ # 验证模块 url(r'^', include('verifications.urls')), ]
- 在md下创建libs目录用于存放发短信的api
- 在CAHES中添加短信验证码的缓存
"verify_codes": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://192.168.103.132:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } },
- 添加发送短信视图
from django.shortcuts import render from rest_framework.views import APIView import random, logging from django_redis import get_redis_connection from rest_framework.response import Response from rest_framework import status from md.libs.yuntongxun.sms import CCP from . import constants loger = logging.getLogger('django') # Create your views here. class SMSCodeView(APIView): def get(self, requset, mobile): # 链接redis redis_conn = get_redis_connection('verify_codes') # 查看是否重发发送 send_flag = redis_conn.get('send_flag_%s' % mobile) if send_flag: return Response({'message': '频发发送'}) sms_code = '%06d' % random.randint(0, 999999) loger.info(sms_code) # 保存短信你 redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code) # 添加标记(一分钟重复发送) redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1) CCP().send_template_sms(to=mobile, datas=[sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], temp_id=1) return Response({'message': 'OK'})
- 实现异步和redis优化
- 安装selery模块
pip install selery
- 在项目目录下创建celery_tasks用于保存celery任务
- 在celery_tasks下创建配置文件config.py保存配置信息
# redis 14 号库存放任务对 broker_url = "redis://127.0.0.1/14"
- 在celery_tasks下创建配置文件main.py用于启动selery
from celery import Celery # 为celery使用django配置文件进行设置 import os if not os.getenv('DJANGO_SETTINGS_MODULE'): os.environ['DJANGO_SETTINGS_MODULE'] = 'md.settings.dev' # 创建celery应用 app = Celery('md') # 导入celery配置 app.config_from_object('celery_tasks.config') # 自动注册celery任务 app.autodiscover_tasks(['celery_tasks.sms'])
- 在celery_tasks下创建sms用于存放发短信业务
- 将提供的发送短信的云通讯SDK放到celery_tasks/sms/目录下。
- 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)
- 启动selery
celery -A celery_tasks.main worker
- 更改发短信视图
from celery_tasks.sms import tasks as sms_tasks class SMSCodeView(GenericAPIView): ... # CCP().send_template_sms(to=mobile, datas=[sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], temp_id=1) # 改用异步发送短信 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"})
- 安装selery模块