1.后端代码
具体代码如下:
# GET /api/v1.0/sms_codes/<mobile>?image_code=xxxx&image_code_id=xxxx
@api.route("/sms_codes/<re(r'1[34578]\d{9}'):mobile>")
def get_sms_code(mobile):"""获取短信验证码"""# 获取参数image_code = request.args.get("image_code")image_code_id = request.args.get("image_code_id")# 校验参数if not all([image_code_id, image_code]):# 表示参数不完整return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")# 业务逻辑处理# 从redis中取出真实的图片验证码try:real_image_code = redis_store.get("image_code_%s" % image_code_id)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="redis数据库异常")# 判断图片验证码是否过期if real_image_code is None:# 表示图片验证码没有或者过期return jsonify(errno=RET.NODATA, errmsg="图片验证码失效")# 删除redis中的图片验证码,防止用户使用同一个图片验证码验证多次try:redis_store.delete("image_code_%s" % image_code_id)except Exception as e:current_app.logger.error(e)# 与用户填写的值进行对比if real_image_code.lower() != image_code.lower():# 表示用户填写错误return jsonify(errno=RET.DATAERR, errmsg="图片验证码错误")# 判断对于这个手机号的操作,在60秒内有没有之前的记录,如果有,则认为用户操作频繁,不接受处理try:send_flag = redis_store.get("send_sms_code_%s" % mobile)except Exception as e:current_app.logger.error(e)else:if send_flag is not None:# 表示在60秒内之前有过发送的记录return jsonify(errno=RET.REQERR, errmsg="请求过于频繁,请60秒后重试")# 判断手机号是否存在try:user = User.query.filter_by(mobile=mobile).first()except Exception as e:current_app.logger.error(e)else:if user is not None:# 表示手机号已存在return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在")# 如果手机号不存在,则生成短信验证码sms_code = "%06d" % random.randint(0, 999999)# 保存真实的短信验证码try:redis_store.setex("sms_code_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)# 保存发送给这个手机号的记录,防止用户在60s内再次出发发送短信的操作redis_store.setex("send_sms_code_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="保存短信验证码异常")# 发送短信# 使用celery异步发送短信, delay函数调用后立即返回(非阻塞)# send_sms.delay(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)], 1)# 返回异步任务的对象result_obj = send_sms.delay(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)], 1)print(result_obj.id)# 通过异步任务对象的get方法获取异步任务的结果, 默认get方法是阻塞的ret = result_obj.get()print("ret=%s" % ret)# 返回值# 发送成功return jsonify(errno=RET.OK, errmsg="发送成功")
2.前端html代码
具体代码如下:
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>爱家-注册</title><link href="/static/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"><link href="/static/css/reset.css" rel="stylesheet"><link href="/static/css/ihome/main.css" rel="stylesheet"><link href="/static/css/ihome/register.css" rel="stylesheet">
</head>
<body><div class="container"><div class="logo-bar"><a href="/"><img src="/static/images/logo@128x59.png"></a></div><form class="form-register"><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-mobile fa-2x fa-fw"></i></div><input type="number" class="form-control" name="mobile" id="mobile" placeholder="手机号" required></div></div><div class="error-msg" id="mobile-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-image fa-lg fa-fw"></i></div><input type="text" class="form-control" name="imagecode" id="imagecode" placeholder="图片验证码" required><div class="input-group-addon image-code" onclick="generateImageCode();"><img src=""></div></div></div><div class="error-msg" id="image-code-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-envelope-o fa-lg fa-fw"></i></div><input type="text" class="form-control" name="phonecode" id="phonecode" placeholder="短信验证码" required><div class="phonecode input-group-addon"><a class="phonecode-a" href="javascript:;" onclick="sendSMSCode();">获取验证码</a></div></div></div><div class="error-msg" id="phone-code-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></div><input type="password" class="form-control" name="password" id="password" placeholder="密码" required></div></div><div class="error-msg" id="password-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></div><input type="password" class="form-control" name="password2" id="password2" placeholder="确认密码" required></div></div><div class="error-msg" id="password2-err"><i class="fa fa-exclamation-circle"></i><span></span></div><button type="submit" class="btn btn-lg btn-theme btn-block">立即注册</button><p class="login-a">已有账号,<a href="/login.html">立即登陆</a></p></form></div><script src="/static/js/jquery.min.js"></script><script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script><script src="/static/js/ihome/register.js"></script>
</body>
</html>
3.前端js代码
具体代码如下:
function sendSMSCode() {// 点击发送短信验证码后被执行的函数$(".phonecode-a").removeAttr("onclick");var mobile = $("#mobile").val();if (!mobile) {$("#mobile-err span").html("请填写正确的手机号!");$("#mobile-err").show();$(".phonecode-a").attr("onclick", "sendSMSCode();");return;} var imageCode = $("#imagecode").val();if (!imageCode) {$("#image-code-err span").html("请填写验证码!");$("#image-code-err").show();$(".phonecode-a").attr("onclick", "sendSMSCode();");return;}// 构造向后端请求的参数var req_data = {image_code: imageCode, // 图片验证码的值image_code_id: imageCodeId // 图片验证码的编号,(全局变量)};// 向后端发送请求$.get("/api/v1.0/sms_codes/"+ mobile, req_data, function (resp) {// resp是后端返回的响应值,因为后端返回的是json字符串,// 所以ajax帮助我们把这个json字符串转换为js对象,resp就是转换后对象if (resp.errno == "0") {var num = 60;// 表示发送成功var timer = setInterval(function () {if (num >= 1) {// 修改倒计时文本$(".phonecode-a").html(num + "秒");num -= 1;} else {$(".phonecode-a").html("获取验证码");$(".phonecode-a").attr("onclick", "sendSMSCode();");clearInterval(timer);}}, 1000, 60)} else {alert(resp.errmsg);$(".phonecode-a").attr("onclick", "sendSMSCode();");}});
}