Django项目之电商购物商城 – 短信验证码生成
需要开发文档和前端资料的可私聊
一. 调用外部接口发送短信验证码
发送短信验证码的功能使用:https://console.yuntongxun.com/member/main
安装:pip install ronglian_sms_sdk
在应用下创建一个包实现发送短信的功能 —— ronglianyun , 创建模块: ccp_sms
二. 创建发送验证码的实例
import json from ronglian_sms_sdk import SmsSDK accId = '2c94811c8cd4da0a018f3549b8d279ac' accToken = '9ac15f4290e44155ad7cf092fa6308cb' appId = '2c94811c8cd4da0a018f3549ba6579b3' class CCP: # 创建单列模式 _instance = None # 使用new静态方法 创建时值分配一个内存空间 , 避免内存的浪费 def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance def send_message(self,mobile,datas): sdk = SmsSDK(accId, accToken, appId) tid = '1' resp = sdk.sendMessage(tid, mobile, datas) resp = json.loads(resp) # 判断短信验证码是否发送成功 if resp["statusCode"] == "000000": # 短信验证码发送成功 return 0 else: return -1 send_code = CCP()
三. 修改前端代码
<li> <label>短信验证码:</label> <input type="text" name="sms_code" id="msg_code" class="msg_input" v-model="sms_code" @blur="check_sms_code"> <a @click="send_sms_code" class="get_msg_code">获取短信验证码</a> <span class="error_tip" v-show="error_sms_code">请填写短信验证码</span> </li>
四. 匹配路由
let url = '/sms_code/'+this.mobile+'/?uuid='+this.uuid+'&image_code='+this.image_code;
路由中含有手机号 , uuid以及用户输入的图盘验证码信息 , 在设置路由中需要匹配用户输入的手机号
# 发送手机验证码 # let url = '/sms_code/'+this.mobile+'/?uuid='+this.uuid+'&image_code='+this.image_code; re_path("^sms_code/(?P<mobile>1[3-9]\d{9})/$", views.SmsCodeView.as_view())
五. 创建视图
实现发送验证码的功能
# 发送短信验证码 class SmsCodeView(View): def get(self , request , mobile): # 校验图片验证码是否正确 # 接受参数中的uuid , 以及图片验证码 uuid = request.GET.get('uuid') image_code_client = request.GET.get('image_code') # 校验数据是否完整 if not all([uuid , image_code_client]): return HttpResponse("参数有误") # 获取redis中的验证码 , 进行验证码的校验 redis_conn = get_redis_connection('var_code') image_code_server = redis_conn.get('image_%s'%uuid) send_flag = redis_conn.get('send_%s' % mobile) if send_flag: return JsonResponse({ 'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信验证码过于频繁' }) # 判断图片验证码是否过期 if image_code_server is None: return JsonResponse({ "code":RETCODE.IMAGECODEERR, "errmsg":"图片验证码失效" }) # 删除图片验证码 redis_conn.delete('image_%s'%uuid) # 判断图片验证码是否正确 image_code_server = image_code_server.decode() if image_code_client.lower() != image_code_server.lower(): return JsonResponse({ "IMAGECODEERR":RETCODE.IMAGECODEERR, "errmsg":"图片验证码错误" }) # 发送短信验证码 # 随机生成四位数验证码 sms_code = random.randint(1000, 9999) redis_conn.setex('image_%s' % mobile, 400, sms_code) # 创建手机表示 redis_conn.setex('send_%s' % mobile, 60, 1) send_code.send_message(mobile=mobile , datas=(sms_code , 5)) return JsonResponse({ "code":RETCODE.OK, "errmsg":"短信验证码发送成功" })
六. 在from组件中校验验证码信息
sms_code = forms.CharField(max_length=4 , min_length=4)
七. 完善登录视图
判断验证码是否正确 , 实现注册功能
class RegisterView(View): def get(self , request): return render(request , 'register.html') def post(self , request): # 将用户数据传入forms组件进行校验 register_forms = RegisterForms(request.POST) if register_forms.is_valid(): # 注册信息无误 username = register_forms.cleaned_data.get('username') password = register_forms.cleaned_data.get('password') mobile = register_forms.cleaned_data.get('mobile') client_code = register_forms.cleaned_data.get('sms_code') redis_conn = get_redis_connection('var_code') server_code = redis_conn.get('image_%s' % mobile) # 判断短信验证是否失效 if server_code is None: return render(request , 'register.html' , {"sms_code_errmsg":"短信验证码失效"}) # 判断短信验证码是否正确 if server_code.decode() != client_code: return render(request , 'register.html' , {"sms_code_errmsg":"短信验证码错误"}) # 保存用户数据入库 user = User.objects.create_user(username=username , password=password , mobile = mobile) login(request , user) return redirect('login') else: # 获得forms组件的异常信息 content = {"forms_err_msg" : register_forms.errors} return render(request , 'register.html' , content)