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": '6',#"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 = ''
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>

python-Web-django-短信登陆的更多相关文章

  1. python 阿里云短信群发推送

    本篇文章是使用Python的Web框架Django提供发送短信接口供前端调用,Python版本2.7 阿里云入驻.申请短信服务.创建应用和模板等步骤请参考:阿里云短信服务入门 1.下载sdk 阿里云短 ...

  2. python web -- django

    一. 安装 django $ pip install django (env)$ python >> import django >> django.VERSION >& ...

  3. python web——Django架构

    环境:windows/linux/OS 需要的软件:Firefox 浏览器(别的也可以 不过firfox和python的webdriver兼容性好) git版本控制系统(使用前要配置 用户 编辑器可以 ...

  4. 用Python免费发短信,实现程序实时报警

    进入正文 今天跟大家分享的主题是利用python库twilio来免费发送短信. 先放一张成品图: 代码放在了本文最后的地址中 正文 眼尖的小伙伴已经发现了上面的短信的前缀显示这个短信来自于一个叫Twi ...

  5. Python twilio发短信实践

    twilio注册地址   注册的时候可能会报错   最好是*** -->注册-->注册完毕后代码运行是不需要***的 https://www.twilio.com/console 需要pi ...

  6. zabbix 利用python脚本实现短信告警

    一.编写脚本 cd /usr/local/zabbix-4.0.3/share/zabbix/alertscripts vi zabbix_sms.py 内容如下: #!/usr/bin/python ...

  7. 基于阿里云平台的使用python脚本发送短信

    第一步:点击短信服务下的帮助文档 第二步:安装python的SDK:点击安装python sdk 第三步:直接通过python的pip工具安装即可,方便快捷: 第四步:点击红框进行测试: 第五步:测试 ...

  8. 青龙+Nvjdc短信登陆对接Xdd-plus推送+Ninja CK登陆教程(11.23更新)

    一.准备工作 1.shh工具(powshell.gitbash等等) 2.购买一台云服务器(阿里云.腾讯云都可以) 3.安装宝塔面板 宝塔Linux面板安装教程 - 2021年8月18日更新 - 7. ...

  9. python免费发送短信

    pip install twilio from twilio.rest import Client # Your Account SID from twilio.com/console account ...

  10. python 实现发送短信验证码

    [说明]短信接口使用的是“聚合数据”上面的接口. 那么在使用接口前,需要在聚合数据上面注册,进行申请接口.当然在正式使用之前,我们可以使用申请免得的进行测试. 一.申请成功后,需做的准备工作如下: 1 ...

随机推荐

  1. STM32F103C8T6最小板搞定CMSIS-DAP和SWO功能

    转载:http://www.stmcu.org.cn/module/forum/forum.php?mod=viewthread&tid=616081&extra=page%3D&am ...

  2. Oracle之:Function :strFormatDate()

    create or replace function strFormatDate(i_datestr in varchar2) return date is begin if i_datestr is ...

  3. JAVA 日期操作

    1.用java.util.Calender来实现 Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date()); Sys ...

  4. BZOJ 4128: Matrix (矩阵BSGS)

    类比整数的做法就行了 1A爽哉 #include<bits/stdc++.h> using namespace std; typedef long long LL; const int M ...

  5. 逻辑卷----LVM的基础和应用

    逻辑卷管理器 Logical Volume Manager-------逻辑卷宗管理器.逻辑扇区管理器.逻辑磁盘管理器,是Linux核心所提供的逻辑卷管理(Logical volume managem ...

  6. Win7安装VS2019

    SP1 补丁 WIN7安装VS2019需要更新两个补丁才能顺利安装,否则会闪退. KB4474419 KB4490628 https://zhidao.baidu.com/question/18026 ...

  7. 网络摘抄jdk1.8——jvm分析与调优

    一.JVM空间说明 JDK 1.7及以前,Java 类信息.常量池.静态变量都存储在 Perm(永久代)里.类的元数据和静态变量在类加载的时候分配到 Perm,当类被卸载的时候垃圾收集器从 Perm ...

  8. java 项目 文件关系 扫描 注释注入(2)

    https://www.cnblogs.com/daimajun/p/7152970.html(copy) 先提一嘴 @RequestMapping(“url”),这里的 url写的是请求路径的一部分 ...

  9. luogu 5561 [Celeste-B]Mirror Magic 后缀数组+RMQ+multiset

    思路肯定是没有问题,但是不知道为啥一直 TLE 两个点~ #include <bits/stdc++.h> #define N 2000006 #define setIO(s) freop ...

  10. BZOJ 4042 Luogu P4757 [CERC2014]Parades (树形DP、状压DP)

    题目链接 (BZOJ) https://www.lydsy.com/JudgeOnline/problem.php?id=4042 (Luogu) https://www.luogu.org/prob ...