1.需要准备如下:
验证码图片、对应的验证码
验证码图片和验证码我们可以使用python去生成,代码参考,不懂的话,可以使用AI生成这一段,可以生成比较复杂的
import random
from PIL import Image
import time
import uuid
import os
code = generate_verification_code_test(6)
image_size = (200, 100)
font_size = 40
image = Image.new('RGB', image_size, color='white')
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", font_size)
draw.text((10, 10), code, fill='black', font=font)
# 添加干扰线
for _ in range(5):
draw.line([(random.randint(0, image_size[0]), random.randint(0, image_size[1])),
(random.randint(0, image_size[0]), random.randint(0, image_size[1]))],
fill='black', width=2)
# 添加噪点
for _ in range(100):
draw.point((random.randint(0, image_size[0]), random.randint(0, image_size[1])), fill='black')
filename = str(uuid.uuid4()) + '.jpg'
filename = os.path.join("static\codeimage", filename)
image.save(filename)
time.sleep(2)
# filesave = os.path.join('\codeimage', filename)
verifimhg = validationimage.objects.create(code=code, imageurl=filename)
verifimhg.save()
print(f"验证码第{i}张生成完成")
2.创建一个数据库。包含三个字段,ID,验证码图片,验证码,就像下面这样,下面是数据库内容
303,static\codeimage\d0e5812d-8b8e-4602-b808-71e0e2b3c234.jpg,100S0I
304,static\codeimage\af62a084-6d88-4188-94e0-61b6e8cec1e7.jpg,JWQN43
305,static\codeimage\436db3ce-b3f4-4953-be47-4e13be5cdf8b.jpg,E200UZ
306,static\codeimage\53ad23ef-8119-4c42-a27a-3b81e74785aa.jpg,INHPVV
307,static\codeimage\3bd88aee-68e2-4a39-939d-97a03149e387.jpg,AKXMUP
308,static\codeimage\1a536dc1-5024-4264-b4d9-45923553a924.jpg,8U6DB9
309,static\codeimage\fe3440b9-8631-4de8-89bc-035ca56fe5a2.jpg,H2N83P
310,static\codeimage\e8ddc664-b0c5-4856-8f8c-c992662f88d2.jpg,Y4P0C2
311,static\codeimage\1a5a62fb-3e49-45ed-81d5-b52a1ac77442.jpg,46Q7TL
312,static\codeimage\9d95d569-97fb-42b0-a14d-8ff81e266a7f.jpg,2YKNNW
313,static\codeimage\c5656e02-7359-4cf4-9049-6256430062e3.jpg,B2O9PX
314,static\codeimage\59de9bbb-10c5-4645-a446-38c73dea15f9.jpg,ZZHVGT
3.发起JavaScript请求
大致思路、产生一个随机数,用来请求数据库中的数据,如验证码,以及验证码图片,随机数范围应该是数据库条数的范围之间,如300条数据,那么随机数应该在1-300之间,
JavaScript代码
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function imagesfun() {
var image = document.getElementById("vaildimg")
// 示例:生成 1 到 300 之间的随机整数
var randomNumber = getRandomInt(1, 300); // 区间为 [1, 301),所以实际上生成了 1 到 300 之间的随机整数
console.log(randomNumber);
var formData = new FormData()
formData.append("id",randomNumber);
// 如果Django视图需要CSRF令牌,可以在这里添加
formData.append('csrfmiddlewaretoken', document.querySelector('input[name=csrfmiddlewaretoken]').value);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/verificationimagefun/", true);
xhr.onload = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// console.log(response.data)
// console.log(response)
console.log(response.imagepath)
if (response.data === "OK") {
// alert('验证码刷新成功');
image.src = '\\' +response.imagepath
image.name = randomNumber
// console.log(image.name)
} else {
alert('验证码刷新失败');
}
} else {
alert('验证码刷新失败:' + xhr.statusText);
}
};
xhr.onerror = function() {
alert('验证码刷新失败:网络错误');
};
xhr.send(formData);
}
视图函数,打到id,并返回所在的数据,返回图片位置
def verificationimagefun(request):
if request.method == 'POST':
id = request.POST.get('id')
imagepath = validationimage.objects.all()[int(id)].imageurl
if request.method == 'POST':
id = request.POST.get('id')
# print(id)
# return JsonResponse({'data': "OK"})
return JsonResponse({
'data': "OK",'imagepath':imagepath})
else:
return JsonResponse({
'data':'NG'})