在主函数视图中通过url调用执行函数的代码如下:
@dingdong.route('/send_token/', methods=['POST'])
def send_token():
"""获取手机号,发送验证码"""
phone = request.form.get('phone') # 获取用户填写的手机号
user_id = session['user_id'] # 获取用户ID
vc = set_verification_code(user_id=user_id, phone=phone) # vc:verification_code
try:
ali_send_code(phone=phone, vc=vc) # 发送验证码
except BaseException as err:
print(err)
clear_verification(user_id=user_id, phone=phone) # 发送失败,清除缓存中的验证码信息
return jsonify({'status': 'ok', 'message': '验证码发送成功'})
根据上面的代分析码有三个函数需要具体的定义实现:
第一、set_verification_code()函数
def set_verification_code(user_id, phone, ex: int = 300) -> str:
"""账号绑定验证码"""
vc = generate_vc()
qst_redis.set(name=f'_vc_{user_id}_{phone}', value=vc, ex=ex)
return vc
def generate_vc(length: int = 4) -> str:#产生四位随机数
"""vc:verification_code
:param length: vc长度
:return: vc
"""
result = ''
for _ in range(length):
result += str(random.randint(0, 9))
return result
第二、ali_send_code()函数
from dysms_python.demo_sms_send import send_sms
def ali_send_code(phone, vc) -> bool:
"""发送验证码
:param phone: 手机号
:param vc: verification_code,验证码.由set_verification_code生成.
:return: 发送结果
"""
param = json.dumps({"code": f"{vc}"})
try:
callback = json.loads(send_sms(phone_numbers=phone, template_param=param)) # 阿里云接口
except BaseException as err:
print(err)
return False
if callback.get('Code') == "OK":
return True
else:
print(callback)
return False
demo_sms_send.py的代码如下:
# -*- coding: utf-8 -*-
import sys
import json
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkdysmsapi.request.v20170525 import QuerySendDetailsRequest
from aliyunsdkcore.client import AcsClient
import uuid
from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.http_service import method_type as MT
from aliyunsdkcore.http_service import format_type as FT
import dysms_python.const as const
"""
短信业务调用接口示例,版本号:v20170525
Created on 2017-06-12
"""
try:
reload(sys)
sys.setdefaultencoding('utf8')
except NameError:
pass
except Exception as err:
raise err
# 注意:不要更改
REGION = "cn-hangzhou"
PRODUCT_NAME = "Dysmsapi"
DOMAIN = "dysmsapi.aliyuncs.com"
acs_client = AcsClient(const.ACCESS_KEY_ID, const.ACCESS_KEY_SECRET, REGION)
# region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)
def send_sms(phone_numbers, business_id=None, sign_name='公司名称', template_code='SMS_141597770', template_param=None):
smsRequest = SendSmsRequest.SendSmsRequest()
# 申请的短信模板编码,必填
smsRequest.set_TemplateCode(template_code)
# 短信模板变量参数
if template_param is not None:
smsRequest.set_TemplateParam(template_param)
# 设置业务请求流水号,必填。
if business_id:
smsRequest.set_OutId(business_id)
else:
smsRequest.set_OutId(uuid.uuid4())
# 短信签名
smsRequest.set_SignName(sign_name)
# 数据提交方式
# smsRequest.set_method(MT.POST)
# 数据提交格式
# smsRequest.set_accept_format(FT.JSON)
# 短信发送的号码列表,必填。
smsRequest.set_PhoneNumbers(phone_numbers)
# 调用短信发送接口,返回json
smsResponse = acs_client.do_action_with_exception(smsRequest)
# TODO 业务处理
return smsResponse
# __business_id = uuid.uuid4()
# # print(__business_id)
# params = json.dumps({"code": "klj5"})
# # params = u'{"name":"wqb","code":"12345678","address":"bz","phone":"13000000000"}'
# callback = send_sms(phone_numbers="13088606295", business_id=__business_id, sign_name="趣视听",
# template_code="SMS_116567215", template_param=params)
# print(callback)
第三、clear_verification()函数
def clear_verification(user_id, phone): """清除缓存中的验证码信息""" qst_redis.delete(f'_vc_{user_id}_{phone}')