工具类代码
coding=utf-8
import random
from io import BytesIO
from PIL import Image,ImageFont,ImageDraw
def GetCode():
source = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890'
code = ""
for i in range(4):
code += random.choice(source)
return code
def Set_Color():
return random.randrange(255)
def Send_code_img(request):
color_bg = (Set_Color(), Set_Color(), Set_Color())
image = Image.new("RGB", size=(150, 50), color=color_bg)
imagedraw = ImageDraw.Draw(image, "RGB")
font = ImageFont.truetype("/static/Font/ALGER.TTF", 55)
YanZhen_code = GetCode()
imagedraw.text(xy=(0, 0), text=YanZhen_code, font=font, fill=(255, 255, 255))
request.session["verify_code"]=YanZhen_code
for i in range(800):
# 绘制烦扰点
imagedraw.point(xy=(random.randrange(150), random.randrange(50)), fill=(Set_Color(), Set_Color(), Set_Color()))
# image.show()
fp = BytesIO()
image.save(fp,"png")
return fp.getvalue()
if __name__==”__main__”:
pass
views 的代码
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from APP.TOOLS.YanZhen import Send_code_img
def Mine(request):
return HttpResponse("欢送登录")
@csrf_exempt
def Login(request):
if request.method == "GET":
return render(request, "YanZhen.html")
elif request.method == "POST":
post_code = request.POST.get("Get_code")
verify_code =[PerfectMoney 下载](https://www.gendan5.com/wallet/PerfectMoney.html) request.session.get("verify_code")
if post_code.lower() != verify_code.lower():
return redirect(reverse("APP:Login"))
return redirect(reverse("APP:Mine"))
def Get_code_img(request):
code_img = Send_code_img(request)
return HttpResponse(code_img, content_type='image/png')
HTML 代码
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<title> 验证码验证 </title>
{% load static %}
</head>
<body>
<form action=”{% url “APP:Login” %}” method=”POST” >
<span> 请输出验证码:</span><input type="text" name="Get_code" placeholder="请输出验证码">
<br>
<img id="img" src="{% url"APP:get_code_img"%}">
<br>
<button> 提交 </button>
</form>
</body>
<script type=”text/javascript” src=”{% static ‘JS/JQuery/jquery.js’ %}”></script>
<script>
$(()=>{$("#img").click(()=>{let getpicurl="/app/get_code_img/?pic="+Math.random();
$("#img").attr("src", getpicurl);
console.log(getpicurl);
})
})
</script>
</html>