分类: Python/Ruby
2021-08-19 17:24:03
工具类代码
# 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 = 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代码
{% load static %}
请输入验证码:请输入验证码">
提交
$(()=>{
$("#img").click(()=>{
let getpicurl="/app/get_code_img/?pic="+Math.random();
$("#img").attr("src", getpicurl);
console.log(getpicurl);
})
})