一、下载安装包
pip install aliyun-python-sdk-core-v3
二、打开阿里云短信服务
三、点击图片箭头区域创建view视图代码
四、编辑模板
五、在settings中配置阿里云ACCESSKEY
ALY_ACCESSKEY_ID = "LTAI4G6G1CQL8aVAiakkDgiB"
ALY_ACCESSKEY_SECRET = '9V3fPiDzFAgaTUhJAg8Hd4F41AD2wq'
六、自定义一个MyBaseView.py文件,将阿里云生成好的代码复制进去
def send_sms(phone, data):
client = AcsClient(ALY_ACCESSKEY_ID, ALY_ACCESSKEY_SECRET, 'cn-hangzhou')
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_protocol_type('https')
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('RegionId', "cn-hangzhou")
request.add_query_param('PhoneNumbers', phone)
request.add_query_param('SignName', "美多商城")
request.add_query_param('TemplateCode', "SMS_205880734")
request.add_query_param('TemplateParam', data)
response1 = client.do_action(request)
res = json.loads(str(response1, encoding='utf-8'))
if res["Code"] == "OK":
return True
else:
return False
七、Views代码
class SendSMSCode(APIView):
def post(self,request):
phone = request.data.get("phone")
image_code = request.data.get("image_code")
image_code_uuid = request.data.get("image_code_uuid")
print(phone)
print(image_code_uuid)
print(image_code)
if not all([phone,image_code,image_code_uuid]):
return Response({"code":4005,"msg":"参数不全"})
redis_cli = get_redis_connection("img_code")
redis_img_code = redis_cli.get(image_code_uuid).decode()
print(redis_img_code)
print(image_code)
if image_code.lower() != redis_img_code.lower():
return Response({"code":4003,"msg":"参数错误"})
num = random.randint(100000,999999)
print(num)
send_data = {"code":num}
send_sms(phone,send_data)
pl = redis_cli.pipeline()
pl.setex(phone,60*5,num)
pl.delete(image_code_uuid)
pl.execute()
return Response({"code":0,"msg":"发送成功"})