手机号获取验证码:django版本2.2/ js

(venv)虚拟环境安装django版本2.2.12

        pip install django==2.2.12 -i https://pypi.tuna.tsinghua.edu.cn/simple/

(1)根目录创建static / js 文件下放入axios.js 和 qs.min.js 文件

(2)settings配置         templates模板页面 / 静态资源

TEMPLATES = [
    'DIRS': [os.path.join(BASE_DIR), 'templates'],
]
STATIC_URL = '/static/'
STATICFILES_DIRS = ('static',)

(3)根目录创建templates文件 注册login.html模板页面

(4)JS前端原生

<!doctype html>
<html lang="en">
<head>
       
    <meta charset="UTF-8">
       
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
       
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
       
    <script src="/static/js/axios.js"></script>
       
    <script src="/static/js/qs.min.js"></script>
        <title>登陆</title>
</head>
<body>
    <!-- 页面样式 -->
   
<style>
    .login {
        background-color: lightblue;
        margin: 10px auto;
        width: 98%;
    }

    .login input {
        display: inline-block;
        margin-left: 30%;
        width: 40%;
        margin-top: 10px;
        margin-bottom: 10px;
    }

</style>
    <!-- 页面内容 -->
   
<div class="login">
    {% csrf_token %}
    <input id="mobile" type="text" name="mobile" placeholder="手机号">
           
    <button onclick="genCode()">生成验证码</button>
    <br>
    <input id="smsCode" type="text" name="smsCode" placeholder="验证码" onblur="testCode()">
       
</div>

    <!-- 页面交互 -->
    <script type="text/javascript">
        function genCode(){
            console.log("生成验证码....")
            axios.get("/v1/sms_code/",{
                params:{
                    mobile:document.getElementById("mobile").value
                }
            })
            .then(res => {
                console.log('生成验证码的响应:',res)
                if(res.data.code == 200){
                    alert(res.data.smsCode)
                }else{
                    alert(res.data.msg)
                }
            })
            .catch(err => {
                console.log("声称验证码错误:",err)
            })
        }

    function testCode() {
        axios.post("/v1/sms_code/", Qs.stringify({
            mobile: document.getElementById("mobile").value,
            smsCode: document.getElementById("smsCode").value,
            csrfmiddlewaretoken: document.getElementsByName("csrfmiddlewaretoken")[0].value
        }))
            .then((res) => {
                console.log("验证的响应:", res)
                if (res.data.code == 200) {
                    alert(res.data.msg)
                } else {
                    alert(res.data.msg)
                }
            }).catch((err) => {
            console.log("验证失败", err)
        });
    }
</script>
</body>
</html>

(5)view后端视图

from django.views import View
from django.shortcuts import render
from django.http import JsonResponse
import random
import redis

conn = redis.Redis(host="localhost", port=6379)


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')


# 短信验证码
class SmsCodeView(View):
    def get(self, request):
        mobile = request.GET.get('mobile')

        # 生成随机验证码
        sms_code = random.randint(10000, 99999)

        # 验证码存入redis
        key = mobile
        conn.set(key, sms_code, ex=5 * 60)

        return JsonResponse({
            "code": 200,
            'msg': "获取验证码成功",
            'smsCode': sms_code
        })

    def post(self, request):
        # 接收数据
        mobile = request.POST.get('mobile')
        sms_code = request.POST.get('smsCode')

        print("xxxxxx", mobile, sms_code)

        key = mobile

        # 从redis中取出 已存的验证码
        stored_code = conn.get(key)

        if stored_code:
            if stored_code.decode() == sms_code:
                return JsonResponse({
                    "code": 200,
                    'msg': "验证成功"
                })
            else:
                return JsonResponse({
                    "code": 400,
                    "msg": "验证失败"
                })
        else:
            return JsonResponse({
                'code': 400,
                'msg': "验证码已过期"
            })

(6)路由配置

from test_sms_code import views

urlpatterns = [
    path('v1/login/', views.LoginView.as_view()),
    path('v1/sms_code/', views.SmsCodeView.as_view()),
]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值