Django中生成随机验证码(pillow模块的使用)

时间:2023-03-08 16:02:49

Django中生成随机验证码

1、html中a标签的设置

 <img src="/get_validcode_img/" alt="">

2、views中的get2、views中的getvalidcode_img设置

导入文件

 import json
import os
import random
from django.contrib import auth
from django.shortcuts import render, redirect, HttpResponse
from django.forms import Form
from django.forms import fields
from django.forms import widgets
from django.core.exceptions import ValidationError
from django.conf import settings
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO

方法配置

 def get_validcode_img(request):
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 生成一个颜色随机的大小为160,30的图片
img = Image.new(mode="RGB", size=(160, 30), color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# 设置图片的绘制颜色
draw = ImageDraw.Draw(img, "RGB")
# 设置图片的绘制字体(只写字体名,会默认在系统的Fonts下去找)
# font_path = os.path.join(settings.BASE_DIR, "static", "font", "kumo.ttf")
# font = ImageFont.truetype(font_path, 25)
font = ImageFont.truetype(r'C:\Windows\Fonts\Arial.ttf', 25)
# font = ImageFont.truetype(r'C:\中文\kumo.ttf', 25) # 中文路径无法识别 # 设置图片上的字符串
valid_list = []
for i in range(5):
random_num = str(random.randint(0, 9))
random_letter_low = chr(random.randint(65, 90))
random_letter_upper = chr(random.randint(96, 122))
random_char = random.choice([random_num, random_letter_low, random_letter_upper]) # 随机选择字符(数字,大小写字母)
# 通过draw.text方法,设置图片上字符串的x,y坐标,字符串,颜色,字体(for循环5次,生成5个字符的验证码)
draw.text([5+i*25, 10], random_char, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), font=font)
valid_list.append(random_char)
# 获取一个内存中的文件句柄
f = BytesIO()
# 在文件句柄中写入文件
img.save(f, 'png')
# 取出文件
data = f.getvalue()
# 转换成字符串
valid_str = "".join(valid_list)
print(valid_str) # 把验证码保存在session中,当用户出入验证码发送请求的时候,把用户输入的数据和session中的验证码做对比
request.session["validcode"] = valid_str
return HttpResponse(data)

三、 Ajax请求配置

 $(function(){
$("#login_btn").click(function () {
var username = $("#username").val();
var password = $("#password").val();
var validcode = $("#validcode").val(); $.ajax({
url: "/login/",
type: "POST",
data : {"username":username, "password":password, "validcode":validcode},
headers: {"X-CSRFToken": $.cookie("csrftoken")}, //配置csrftoken
success: function (data) {
console.log(data);
var response = JSON.parse(data);
if (response["is_login"]){
self.location.href = ("/index/")
}else{
$(".error").html(response["error_msg"]).css("color","red")
}
}
})
})
})

四、login登录函数配置

 def login(request):
if request.method == "GET":
return render(request, "login.html")
elif request.method == "POST":
print(request.POST)
# 1,获取用户输入信息
username = request.POST.get("username")
password = request.POST.get("password")
validcode = request.POST.get("validcode")
session_validcode = request.session.get('validcode')
# 设置ajax请求的返回数据
login_response = {"is_login": False, "error_msg": None}
# 首先验证验证码输入是否正确
if validcode.upper() == session_validcode.upper():
# 通过auth模块,验证用户名和密码是否正确
user = auth.authenticate(username=username, password=password)
print(user)
if user:
# 验证成功则在返回数据中标志True
login_response['is_login'] = True
# 同时设置用户session
auth.login(request, user) # request.session[is_login] = True
else:
login_response['error_msg'] = "用户名或密码错误"
else:
login_response['error_msg'] = "验证码错误"
print(login_response)
return HttpResponse(json.dumps(login_response))

相关文章