以下是我的代码,我之前用的是腾讯云➕ajax实现给手机发送验证码,但我现在想更换成阿里云的,我应该如何更改?
阿里云短信验证代码
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
import random
code = random.randrange(100000, 999999)
def create_client(access_key_id, access_key_secret):
config = open_api_models.Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret
)
config.endpoint = f'dysmsapi.aliyuncs.com'
return Dysmsapi20170525Client(config)
def send_sms():
client = create_client('LTAI5tBxR8DkU1BKW39QsiLK', 'TEjXlIqcV31dBwwW8gHqUA6xVSr4DO')
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
sign_name='Python图书管理',
template_code=' SMS_470245020',
phone_numbers='15293926739',
# template_param='{"code":"4567"}'
template_param='{"code":"' + str(code) + '"}'
)
runtime = util_models.RuntimeOptions()
try:
# 复制代码运行请自行打印 API 的返回值
client.send_sms_with_options(send_sms_request, runtime)
except Exception as error:
# 如有需要,请打印 error
UtilClient.assert_as_string(error.message)
return send_sms_request
print(send_sms())
之前的腾讯云代码
def send_sms_single(phone_num, template_id, template_param_list):
"""
单条发送短信
:param phone_num:手机号
:param template_id:腾讯云短信模板ID
:param template_param_list:短信模板所需参数列表,例如【验证码:{1},描述:{2},则传递参数】
:return:
"""
appid = settings.TENCENT_SMS_APP_ID # 自己应用ID
appkey = settings.TENCENT_SMS_APP_KEY # 自己应用key
sms_sign = settings.TENCENT_SMS_SIGN # 自己腾讯云创建签名时填写的签名内容
sender = SmsSingleSender(appid, appkey)
try:
response = sender.send_with_param(86, phone_num, template_id, template_param_list, sign=sms_sign)
except HTTPError as e:
print(e)
response = {'result': 1000, 'errmsg': "网络异常发送失败"}
return response
class SendSmsForm(forms.Form):
mobile = forms.CharField(label="手机号", validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = request
def clean_mobile(self):
"""手机号校验的勾子"""
mobile = self.cleaned_data['mobile']
# 判断短信模板是否有问题
tpl = self.request.GET.get('tpl')
template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
if not template_id:
raise ValidationError("短信模板错误")
# 校验数据库中是否已有手机号
exist = Username.objects.filter(mobile=mobile).exists()
if exist:
raise forms.ValidationError('手机号已存在')
# 发短信 & 写redis
code = random.randrange(100000, 999999)
sms = send_sms_single(mobile, template_id, [code, ])
if sms['result'] != 0:
raise ValidationError("短信发送失败,{}".format(sms['errmsg']))
# 验证码写入redis
conn = get_redis_connection()
conn.set(mobile, code, ex=60)
return mobile
def send_sms(request):
"""发送短信"""
form = SendSmsForm(request, data=request.GET)
# 校验手机号,不能为空
if form.is_valid():
return JsonResponse({'status': True})
return JsonResponse({'status': False, 'error': form.errors})
# 腾讯云短信应用 app_id
TENCENT_SMS_APP_ID = 1400302209
# 腾讯云短信应用 app_key
TENCENT_SMS_APP_KEY = '8cc5bf076454953306eb668187930004'
# 腾讯云短信签名内容
TENCENT_SMS_SIGN = "Python之路"
TENCENT_SMS_TEMPLATE = {
'register': 548760,
'login': 548762
}