先安装SDK,执行命令:pip install alibabacloud_dysmsapi20170525==2.0.24
1.根据阿里文档定义一个发送验证码的类方便调用
from alibabacloud_dysmsapi20170525.client import Client
from alibabacloud_tea_openapi.models import Config
from alibabacloud_dysmsapi20170525.models import SendSmsRequest
from alibabacloud_tea_util.models import RuntimeOptions
import json
class Send_SMS():
access_key_id = 'xxxxxxxxxxxxxxx'
access_key_secret = 'xxxxxxxxxxxx'
endpoint = 'dysmsapi.aliyuncs.com'
sign_name = '阿里云短信测试'
template_code = 'SMS_154950909'
def __init__(self):
self.config = Config(
# 必填,您的 AccessKey ID,
access_key_id=self.access_key_id,
# 必填,您的 AccessKey Secret,
access_key_secret=self.access_key_secret,
endpoint=self.endpoint
)
def send(self, mobile: str, code: str):
"""
mobile: 手机号
code:验证码
"""
# 1. 创建一个客服端
client = Client(self.config)
send_sms_request = SendSmsRequest(
phone_numbers=mobile,
template_param=json.dumps({"code": code}),
sign_name=self.sign_name,
template_code=self.template_code,
)
# 2. 创建短信对象
# 3. 设置允许时间选项
runtime = RuntimeOptions()
#
try:
# 4. 发送短信
res = client.send_sms_with_options(send_sms_request, runtime)
if res.body.code == 'OK':
return {'code': "OK", "message": "短信发送成功!"}
else:
return {'code': "NO", "error": res.body.message}
except Exception as e:
return {'code': "NO", "message": "短信发送失败!"}
2.视图类的实现
class SendSMSView(APIView):
""" 发送短信 """
def post(self, request):
mobile = request.data.get('mobile')
res = re.match(r'^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$', mobile)
if not res:
return Response({"error": "无效的手机号"}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
else:
# 1. 生成一个随机的验证码
code = self.get_random_code()
# 2. 发送短信
res_info = Send_SMS().send(mobile=mobile, code=code)
if res_info['code'] == 'OK':
# 将短信验证码入库
vcode = VerifCode.objects.create(mobile=mobile,code=code)
res_info['codeID'] = vcode.id
return Response(res_info, status=status.HTTP_200_OK)
else:
return Response(res_info, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def get_random_code(self):
""" 随机生成6位数的验证码 """
code = ''.join([random.choice(string.digits) for _ in range(6)])
return code