博客园生成随机的字符串进行验证
查看黄色标记的
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Signin Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body style="background-color: #eeeeee"> <div class="container"> <div class="col-md-4 row" style="margin: 100px 370px; "> <form class="form-signin"> {% csrf_token %} <h2 class="form-signin-heading text-center">欢迎登陆</h2> <label for="inputuser" class="sr-only">User</label> <input type="text" name="user" id="InputUser" class="form-control" placeholder="请输入用户名" required="" autofocus=""> <label for="inputPassword" class="sr-only">Password</label> <input type="password" name="pwd" id="InputPassword" class="form-control" placeholder="请输入密码" required=""> <div class="row"> <div class="col-md-6"><input type="text" name="ValidNum" id="valid_code" class="form-control" placeholder="请输入验证码" required=""> </div> <div class="col-md-6"><img src="/get_valid_img/" alt=""></div> ###给图片加一个视图函数 ,每次打开都会有两次请求 </div> <span id="error" style="color:red;"></span> <input id="submit" type="button" class="btn btn-lg btn-primary btn-block" value="登录"> </form> <span>账号:alex;密码:alex3714</span> </div> </div> <!-- /container --> </body> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> <script> $(document).ready(function () { $("#submit").on("click", function () { $.ajax({ url: "/login/", type: "post", data: { "inputuser": $("#InputUser").val(), "inputpwd": $("#InputPassword").val(), "csrfmiddlewaretoken": $('[name="csrfmiddlewaretoken"]').val() }, success: function (data) { dataobj = JSON.parse(data); var statues = dataobj.status; var msg = dataobj.msg; if (statues) { location.href = "/homepage/" } else { $("#error").text(msg) } } }) }) }) </script> </html>
生成随机图片的方式一:
def get_valid_img(request): from PIL import Image #引入image模块,pip3 install pillow 用来操作图片的 import random #用于随机的操作 def get_random_color(): #此函数用于定义一个三基色 return (random.randint(0,255),random.randint(0,255),random.randint(0,255)) image = Image.new(mode="RGB",size=(260,40), color=get_random_color()) #生成了随机颜色的图片 f = open("a.png","wb") image.save(f,"png") #把生成的图片保存到硬盘上 with open("a.png","wb") as f_obj: data = f_obj.read() #读取文件的数据 return HttpResponse(data)
def get_valid_img(request): from PIL import Image from io import BytesIO #可以把数据放在内存中 import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 生成图片 image = Image.new(mode="RGB", size=(160, 33), color=get_random_color()) f = open("a.png", "wb") image.save(f, "png") # 读取图片数据 with open('a.png', "rb") as f_read: data = f_read.read() return HttpResponse(data)
第二种生成随机图片:
def get_valid_img(request): from PIL import Image from io import BytesIO #可以把数据放在内存中 import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 生成图片 image = Image.new(mode="RGB", size=(160, 33), color=get_random_color()) f = BytesIO() image.save(f , "png") #存在内存中 data = f.getvalue() #读出数据 return HttpResponse(data)
以上两种方法的区别就是:
第一种是把生成的图片放在硬盘上,每次都要去读取硬盘才能传输数据
第二种是把生成的图片直接保存到内存中,不用每次都读硬盘取数据,这样在能节省读取的时间,取到数据后内存都会清理。
为图片打点:
def get_valid_img(request): from PIL import Image,ImageDraw #为图片打点引入 from io import BytesIO #可以把数据放在内存中 import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 生成图片 width=160 height=33 image = Image.new(mode="RGB", size=(width,height), color=get_random_color()) draw = ImageDraw.Draw(image,mode="RGB") #对生成的图片进行操作 for i in range(100): draw.point((random.randint(0,width),random.randint(0,height)),fill=get_random_color()) #对生成的图片进行打点100次,选好打点的范围,打点的颜色 f = BytesIO() image.save(f , "png") #存在内存中 data = f.getvalue() #读出数据 return HttpResponse(data)

把数值加到这个图画中:
from django.shortcuts import render,HttpResponse,redirect from django.contrib import auth # Create your views here. def homepage(request): return render(request,"homepage.html") import json def login(request): if request.method =="POST": user=request.POST.get("inputuser") pwd=request.POST.get("inputpwd") print(user,pwd) user = auth.authenticate(username=user,password=pwd) if user: auth.login(request,user) data={"status":1,"msg":"登录成功"} else: data = {"status": 0, "msg": "账号或者密码错误"} return HttpResponse(json.dumps(data)) return render(request,"login.html") def get_valid_img(request): from PIL import Image,ImageDraw,ImageFont #为图片打点引入 ,为图片引入数字 from io import BytesIO #可以把数据放在内存中 import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_random_char(): random_num= str(random.randint(0,9)) #生成随机的数字 random_upper_alph=chr(random.randint(65,90)) #生成随机的大写字母 random_lower_alph = chr(random.randint(97, 122)) #生成随机的小写字母 random_char= random.choice([random_num,random_upper_alph,random_lower_alph]) #选择一个上面3个的一个 return random_char width=160 height=33 image = Image.new(mode="RGB", size=(width,height), color=get_random_color()) draw = ImageDraw.Draw(image,mode="RGB") font = ImageFont.truetype("static/kumo.ttf",32) #引入字体的样式 valid_code_str="" for i in range(1,5): char= get_random_char() #获得一个随机的数值 valid_code_str += char #吧获得的值添加到新的字符串中,为下一步的seesion做准备 draw.text([i*30,0],char,get_random_color(),font=font) #把获得的数值打印到图片中,[坐标x,y],需要画的值,值得颜色,字体样式 for i in range(100): draw.point((random.randint(0,width),random.randint(0,height)),fill=get_random_color()) f = BytesIO() image.save(f , "png") #存在内存中 data = f.getvalue() #读出数据 return HttpResponse(data)

为图像画线:
from django.shortcuts import render,HttpResponse,redirect from django.contrib import auth # Create your views here. def homepage(request): return render(request,"homepage.html") import json def login(request): if request.method =="POST": user=request.POST.get("inputuser") pwd=request.POST.get("inputpwd") print(user,pwd) user = auth.authenticate(username=user,password=pwd) if user: auth.login(request,user) data={"status":1,"msg":"登录成功"} else: data = {"status": 0, "msg": "账号或者密码错误"} return HttpResponse(json.dumps(data)) return render(request,"login.html") def get_valid_img(request): from PIL import Image,ImageDraw,ImageFont from io import BytesIO import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_random_char(): random_num= str(random.randint(0,9)) random_upper_alph=chr(random.randint(65,90)) random_lower_alph = chr(random.randint(97, 122)) random_char= random.choice([random_num,random_upper_alph,random_lower_alph]) return random_char width=160 height=33 image = Image.new(mode="RGB", size=(width,height), color=get_random_color()) draw = ImageDraw.Draw(image,mode="RGB") font = ImageFont.truetype("static/kumo.ttf",32) valid_code_str="" for i in range(1,5): char= get_random_char() valid_code_str += char draw.text([i*30,0],char,get_random_color(),font=font) for i in range(100): draw.point((random.randint(0,width),random.randint(0,height)),fill=get_random_color()) #图片画线 for i in range(5): x1 = random.randint(0,width) x2 = random.randint(0,width) y1= random.randint(0,height) y2= random.randint(0,height) draw.line((x1,y1,x2,y2),fill=get_random_color()) #标出起始点和结束点 f = BytesIO() image.save(f , "png") #存在内存中 data = f.getvalue() #读出数据 return HttpResponse(data)

图片画圈:
from django.shortcuts import render,HttpResponse,redirect from django.contrib import auth # Create your views here. def homepage(request): return render(request,"homepage.html") import json def login(request): if request.method =="POST": user=request.POST.get("inputuser") pwd=request.POST.get("inputpwd") print(user,pwd) user = auth.authenticate(username=user,password=pwd) if user: auth.login(request,user) data={"status":1,"msg":"登录成功"} else: data = {"status": 0, "msg": "账号或者密码错误"} return HttpResponse(json.dumps(data)) return render(request,"login.html") def get_valid_img(request): from PIL import Image,ImageDraw,ImageFont #为图片打点引入 ,为图片引入数字 from io import BytesIO #可以把数据放在内存中 import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_random_char(): random_num= str(random.randint(0,9)) #生成随机的数字 random_upper_alph=chr(random.randint(65,90)) #生成随机的大写字母 random_lower_alph = chr(random.randint(97, 122)) #生成随机的小写字母 random_char= random.choice([random_num,random_upper_alph,random_lower_alph]) #选择一个上面3个的一个 return random_char # 生成图片 width=160 height=33 image = Image.new(mode="RGB", size=(width,height), color=get_random_color()) draw = ImageDraw.Draw(image,mode="RGB") #对生成的图片进行操作 font = ImageFont.truetype("static/kumo.ttf",32) #引入字体的样式 valid_code_str="" for i in range(1,5): char= get_random_char() #获得一个随机的数值 valid_code_str += char #吧获得的值添加到新的字符串中,为下一步的seesion做准备 draw.text([i*30,0],char,get_random_color(),font=font) #把获得的数值打印到图片中,[坐标x,y],需要画的值,值得颜色,字体样式 for i in range(100): draw.point((random.randint(0,width),random.randint(0,height)),fill=get_random_color()) #对生成的图片进行打点100次,选好打点的范围,打点的颜色 #图片画线 for i in range(5): x1 = random.randint(0,width) x2 = random.randint(0,width) y1= random.randint(0,height) y2= random.randint(0,height) draw.line((x1,y1,x2,y2),fill=get_random_color()) #图片画圈 for i in range(5): draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color()) x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 5, y + 5), 0, 360, fill=get_random_color()) f = BytesIO() image.save(f , "png") #存在内存中 data = f.getvalue() #读出数据 return HttpResponse(data)

为了验证验证码,我们需要把验证码注册到session中,方便在POST请求的登录验证。
from django.shortcuts import render,HttpResponse,redirect from django.contrib import auth # Create your views here. from django.http import JsonResponse #用这种方法传值到ajax不需要json序列化了,前端也不需要反序列化 def homepage(request): return render(request,"homepage.html") def login(request): if request.is_ajax(): #判断是否用ajax提交的请求 user=request.POST.get("inputuser") pwd=request.POST.get("inputpwd") validcode=request.POST.get("validcode") print(user,pwd,validcode) valid_code_str =request.session.get("valid_code_str") #取得传进session的验证码 loginReaponse={"user":None,"error_msg":""} #定义一个传入值,让后面的每种情况都能进行对次赋值 if validcode.upper()==valid_code_str.upper(): user = auth.authenticate(username=user,password=pwd) if user: auth.login(request,user) loginReaponse["user"]=user.username else: loginReaponse["error_msg"]="账号或者密码错误" else: loginReaponse["error_msg"]="验证码错误" return JsonResponse(loginReaponse) return render(request,"login.html") def get_valid_img(request): from PIL import Image,ImageDraw,ImageFont #为图片打点引入 ,为图片引入数字 from io import BytesIO #可以把数据放在内存中 import random #获得随机的颜色 def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_random_char(): random_num= str(random.randint(0,9)) #生成随机的数字 random_upper_alph=chr(random.randint(65,90)) #生成随机的大写字母 random_lower_alph = chr(random.randint(97, 122)) #生成随机的小写字母 random_char= random.choice([random_num,random_upper_alph,random_lower_alph]) #选择一个上面3个的一个 return random_char # 生成图片 width=160 height=33 image = Image.new(mode="RGB", size=(width,height), color=get_random_color()) draw = ImageDraw.Draw(image,mode="RGB") #对生成的图片进行操作 font = ImageFont.truetype("static/kumo.ttf",32) #引入字体的样式 valid_code_str="" #生产随机的4位验证码 for i in range(1,5): char= get_random_char() #获得一个随机的数值 valid_code_str += char #吧获得的值添加到新的字符串中,为下一步的seesion做准备 draw.text([i*30,0],char,get_random_color(),font=font) #把获得的数值打印到图片中,[坐标x,y],需要画的值,值得颜色,字体样式 for i in range(100): draw.point((random.randint(0,width),random.randint(0,height)),fill=get_random_color()) #对生成的图片进行打点100次,选好打点的范围,打点的颜色 #图片画线 for i in range(5): x1 = random.randint(0,width) x2 = random.randint(0,width) y1= random.randint(0,height) y2= random.randint(0,height) draw.line((x1,y1,x2,y2),fill=get_random_color()) # #图片画圈 # for i in range(5): # draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color()) # x = random.randint(0, width) # y = random.randint(0, height) # draw.arc((x, y, x + 5, y + 5), 0, 360, fill=get_random_color()) f = BytesIO() image.save(f , "png") #存在内存中 data = f.getvalue() #读出数据 request.session["valid_code_str"]=valid_code_str return HttpResponse(data)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Signin Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body style="background-color: #eeeeee"> <div class="container"> <div class="col-md-4 row" style="margin: 100px 370px; "> <form class="form-signin"> {% csrf_token %} <h2 class="form-signin-heading text-center">欢迎登陆</h2> <label for="inputuser" class="sr-only">User</label> <input type="text" name="user" id="InputUser" class="form-control" placeholder="请输入用户名" required="" autofocus=""> <label for="inputPassword" class="sr-only">Password</label> <input type="password" name="pwd" id="InputPassword" class="form-control" placeholder="请输入密码" required=""> <div class="row"> <div class="col-md-6"><input type="text" name="ValidNum" id="ValidCode" class="form-control" placeholder="请输入验证码" required=""> </div> <div class="col-md-6"><img src="/get_valid_img/" alt=""></div> </div> <span id="error" style="color:red;"></span> <input id="submit" type="button" class="btn btn-lg btn-primary btn-block" value="登录"> </form> <span>账号:alex;密码:alex3714</span> </div> </div> <!-- /container --> </body> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> <script> $(document).ready(function () { $("#submit").on("click", function () { $.ajax({ url: "/login/", type: "post", data: { "inputuser": $("#InputUser").val(), "inputpwd": $("#InputPassword").val(), "validcode":$("#ValidCode").val(), "csrfmiddlewaretoken": $('[name="csrfmiddlewaretoken"]').val() }, success: function (data) { if (data.user) { location.href = "/homepage/" } else { $("#error").text(data.error_msg) } } }) }) }) </script> </html>


验证码刷新(只需要在路由后面加一个问号即可):
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Signin Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body style="background-color: #eeeeee"> <div class="container"> <div class="col-md-4 row" style="margin: 100px 370px; "> <form class="form-signin"> {% csrf_token %} <h2 class="form-signin-heading text-center">欢迎登陆</h2> <label for="inputuser" class="sr-only">User</label> <input type="text" name="user" id="InputUser" class="form-control" placeholder="请输入用户名" required="" autofocus=""> <label for="inputPassword" class="sr-only">Password</label> <input type="password" name="pwd" id="InputPassword" class="form-control" placeholder="请输入密码" required=""> <div class="row"> <div class="col-md-6"><input type="text" name="ValidNum" id="ValidCode" class="form-control" placeholder="请输入验证码" required=""> </div> <div class="col-md-6"><img src="/get_valid_img/" alt="" id="ValidPhoto"></div> </div> <span id="error" style="color:red;"></span> <input id="submit" type="button" class="btn btn-lg btn-primary btn-block" value="登录"> </form> <span>账号:alex;密码:alex3714</span> </div> </div> <!-- /container --> </body> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> <script> $(document).ready(function () { //点击刷新验证码 $("#ValidPhoto").click(function () { $(this)[0].src+="?" }); //点击提交事件 $("#submit").on("click", function () { $.ajax({ url: "/login/", type: "post", data: { "inputuser": $("#InputUser").val(), "inputpwd": $("#InputPassword").val(), "validcode":$("#ValidCode").val(), "csrfmiddlewaretoken": $('[name="csrfmiddlewaretoken"]').val() }, success: function (data) { if (data.user) { location.href = "/homepage/" } else { $("#error").text(data.error_msg) } } }) }) }) </script> </html>

浙公网安备 33010602011771号