python-Web-django-短信登陆

二次信任 提交于 2019-11-26 14:03:20

until:

import json, urllib
from urllib.parse import urlencode
# 发送短信
def request2(mobile,num, m="GET"):
    appkey = 'a0d6d54cb54e74478f0eca04bdef'#'abf6ecebfa954395dad7dcc6be7c8'
    url = "http://v.juhe.cn/sms/send"
    params = {
        "mobile": mobile,  # 接收短信的手机号码
        "tpl_id": '66666',#"666666" 短信模板ID,请参考个人中心短信模板设置
        "tpl_value": "#code#=%s"%num,
    # 变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号,请先分别进行urlencode编码后再传递,<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
        "key": appkey,#appkey应用APPKEY(应用详细页查询)
        "dtype": "",  # 返回数据的格式,xml或json,默认json
    }
    params = urlencode(params)
    if m == "GET":
        f = urllib.request.urlopen("%s?%s" % (url, params))
    else:
        f = urllib.request.urlopen(url, params)
    content = f.read()
    res = json.loads(content)
    if res:
        error_code = res["error_code"]
        if error_code == 0:
            # 成功请求
            return 'ok'
            # print(res["result"])
        else:
            return "%s:%s" % (res["error_code"], res["reason"])
            # print("%s:%s" % (res["error_code"], res["reason"]))
    else:
        return "request api error"
        # print("request api error")

 

views:

from django.shortcuts import render,HttpResponse,redirect
from app01.models import *
from app01.utils import sendMsg as sm
import json

def login3(request):
    '''手机验证码'''
    res = {'s':None,'info':None}
    if request.POST.get('sendSms'):
        ''''''
        # 获得phone
        phone = request.POST.get('phone')
        if Phone_auth(phone):
            '''手机号符合规则'''
            pass
        else:
            '''手机号不符合规则'''
            res['s'] = 0
            res['info'] = '手机号不符合规则'
            return HttpResponse(json.dumps(res))
        # 获得4位验证码
        num = Num(4)
        # 验证码保存到request里
        request.session['authcode'] = num
        # 发送短信
        # get = sm.request2(phone,num)
        get = 'ok'
        # 判断是否发送成功
        if get == 'ok':
            '''发送成功'''
            print('发送成功',num)
            res['s'] = 1
            res['info'] = '发送成功'
            return HttpResponse(json.dumps(res))
        else:
            '''发送失败'''
            print('发送失败:{}'.format(get))
            res['s'] = 0
            res['info'] = get
            return HttpResponse(json.dumps(res))

    if request.POST.get('dosubmit'):
        ''''''
        # 获得phone
        phone = request.POST.get('phone')
        authcode = request.POST.get('authcode')
        if authcode != request.session['authcode']:
            '''验证码输入错误'''
            res['s'] = 0
            res['info'] = '验证码输入错误'
            print(res)
            return HttpResponse(json.dumps(res))
        # 获得用户对象
        member_obj = Member.objects.filter(member_tel=phone).first()
        request.session['member_name'] = member_obj.member_name
        request.session['member_id'] = member_obj.id
        # 登陆成功
        res['s'] = 1
        res['info'] = '登陆成功'
        print(res)
        return HttpResponse(json.dumps(res))
    return render(request, 'app01_login3.html', locals())

def Num(n:int)->str:
    '''产生n个随机字符串---根列表 ‘1234567890’  '''
    import random
    str1 = '1234567890'
    phone_list = []

    for i in range(n):
        '''循环n次,添加到列表里'''
        phone_list.append(random.choice(str1))
    return ''.join(phone_list)

def Phone_auth(phone:str)->bool:
    '''手机号规则限定'''
    import re
    if phone == '':
        return False
    elif re.match('^[1][1-8]\d{9}$',phone) is not None:
        return True
    else:
        return False

 

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>手机验证码</title>
</head>
<body>
<form action="" method="post">
    {% csrf_token %}
    手机号<input type="text" name="phone" id="phoneid"><br>
    验证码<input type="text" name="authcode" id="authcodeid">
    <input id="getauthcode" type="button" value="获取验证码"/>
    <input id="nowgma" style="display: none;" type="button" value=""/>
    <br>
    <input class="submit " type="button" id="login" value="登录"/>

</form>
</body>
</html>
<script src="/static/js/jquery.min.js"></script>
<script src="/static/layer/layer.js"></script>
<script>
    $(document).ready(function () {
    {#   js运行     #}
        $('#getauthcode').click(function () {
        {#      获取验证码点击事件      #}
            var phone_str = $.trim($('#phoneid').val());
            var re_str = /^[1][1-8]\d{9}/;
            {#   获取手机号,清空空格和设置正则#}
            if(phone_str == ''){
                {#  手机号为空#}
                layer.msg('手机号不能为空!');
                return false
            }else if(!re_str.test(phone_str)){
                {#  手机号格式不正确#}
                layer.msg('手机号格式不正确!');
                return false
            }else{
                {# 手机号传入服务器 #}
                var formdata = {
                    'phone':phone_str,
                    'sendSms': 1,//代表我是发送短信验证码的请求
                    "csrfmiddlewaretoken":"{{ csrf_token }}"
                };
                $.post('{% url 'app01:login3' %}',formdata,function (data) {
                    {#         接收后端数据           #}
                    if (data['s'] == 0){
                        {# 不成功  #}
                        layer.msg(data['info']);
                        return false
                    }else{
                        {# 发送成功  #}
                        console.log(data);
                        // 启动定时器
                        timeout();
                        layer.msg(data['info']);
                        {#   #}
                    }
                },'json')
            }
        });

        $('#login').click(function(){
            Login()
        });


    function Login() {
        {#        登陆函数#}
        $("#login").click(function () {
        var phone = $.trim($("#phoneid").val());
        var authcode = $.trim($("#authcodeid").val());

        $.post("/login3/", {
            "phone": phone,
            "authcode": authcode,
            "dosubmit": 1,
            "csrfmiddlewaretoken":"{{ csrf_token }}"
        }, function (data) {
            if (data['s'] == 1) {
                alert("登录成功!");
                // 跳转主页面
                location.href="{% url 'app01:index' %}";
            } else {
                alert(data['info']);
            }
            return false;
        }, "json");
    });
    }
    var sec = 60;
    var interval = null;
    //开启定时器
    function timeout() {
        interval = setInterval(run, 1000);
    }
    function run() {
        if (sec >= 1) {
            sec--;
            console.log(sec);
            $("#getauthcode").hide();
            $("#nowgma").show();
            $("#nowgma").val("倒计时(" + sec + ")s");

        } else {
{#            $("#yanzhengma").off('click');#}
{#            $('#yanzhengma').on("click", function (event) {#}
{#                getSmsCode();#}
{#            });#}
            $("#getauthcode").show();
            $("#nowgma").hide();
            clearInterval(interval);//关闭定时器

        }}
    })
</script>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!