这篇文章我们开始完成短信验证码的前后端逻辑 后端逻辑 短信验证码接口设计
class SMSCodeView(View):
"""短信验证码"""
def get(self, request, mobile):
"""
:param mobile: 手机号
:return: JSON
"""
# 接收参数
image_code_client = request.GET.get('image_code')
uuid = request.GET.get('uuid')
# 校验参数
if not all([image_code_client, uuid]):
return HttpResponseForbidden('缺少必传参数')
# 创建连接到redis的对象
redis_conn = get_redis_connection('verify_code')
# 提取图形验证码
image_code_server = redis_conn.get("img_%s" % uuid)
# 删除图形验证码,避免恶意测试图形验证码
redis_conn.delete("img_%s" % uuid)
# 对比图形验证码
if image_code_client != image_code_server.decode():
return JsonResponse({"code": "", "errmsg": '图形验证码输入有误'})
# 生成短信验证码:生成6位数验证码
sms_code = "%06d" % random.randint(0, 999999)
# 保存短信验证码
redis_conn.setex("sms_" % mobile, 300, sms_code)
# 发送短信验证码
CCP().send_message(1, mobile, (sms_code, 5))
# 响应结果
return JsonResponse({"code": "0", "errmsg": '发送短信验证码输入成功'})
优化短信验证码后端逻辑,将一些常量定义在另一文件中 短信验证码前端逻辑实现
check_sms_code() {
if (this.sms_code.length != 6) {
this.error_sms_code_message = '请填写短信验证码';
this.error_sms_code = true;
} else {
this.error_sms_code = false;
}
},
// 发送短信验证码
send_sms_code(){
// 避免频繁点击发送短信验证码标签
if (this.sending_flag == true) {
return;
}
this.sending_flag = true;
// 校验参数
this.check_mobile();
this.check_image_code();
if (this.error_mobile == true || this.error_image_code == true) {
this.sending_flag = false;
return;
}
// 向后端接口发送请求,让后端发送短信验证码
let url = '/sms_codes/' + this.mobile + '/?image_code=' + this.image_code+'&uuid='+ this.uuid;
axios.get(url, {
responseType: 'json'
})
.then(response => {
// 表示后端发送短信成功
if (response.data.code == '0') {
// 倒计时60秒
let num = 60;
let t = setInterval(() => {
if (num == 1) {
clearInterval(t);
this.sms_code_tip = '获取短信验证码';
this.generate_image_code();
this.sending_flag = false;
} else {
num -= 1;
this.sms_code_tip = num + '秒';
}
}, 1000)
} else {
if (response.data.code == '4001') {
this.error_image_code_message = response.data.errmsg;
this.error_image_code = true;
} else { // 4002
this.error_sms_code_message = response.data.errmsg;
this.error_sms_code = true;
}
this.sending_flag = false;
}
})
.catch(error => {
console.log(error.response);
this.sending_flag = false;
})
},
// 校验用户名
check_username() {
let re = /^[a-zA-Z0-9_-]{5,20}$/;
if (re.test(this.username)) {
this.error_name = false;
} else {
this.error_name_message = '请输入5-20个字符用户名';
this.error_name = true;
}
if (this.error_name == false) {
let url = '/users/usernames/' + this.username + '/count/';
axios.get(url, {
responseType: 'json'
})
.then(response => {
if (response.data.count == 1) {
this.error_name_message = '用户名已存在';
this.error_name = true;
} else {
this.error_name = false;
}
})
.catch(error => {
console.log(error.response);
})
}
},
|