前端相关
<img class="validCode_img" src="/get_validCode_img/" alt="" width="160px" height="40px" title="点击更换验证码">
前端src访问这个url会自动生成图片链接
验证码刷新
//url无刷新验证码
$(".validCode_img").click(function () {
this.src+="?";
});
url配置
url(r'^get_validCode_img/',views.get_validCode_img),
后端代码具体实现
# 生成验证码函数
def get_validCode_img(request):
print("===================caonidaye,登陆页面执行")
from io import BytesIO
import random
from PIL import Image,ImageDraw,ImageFont
img = Image.new(mode="RGB", size=(120, 40),color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) #背景
draw = ImageDraw.Draw(img,mode="RGB") #生成一个画笔,可以写东西
draw.point([100, 20], fill="black") #画点-----(坐标,参数)
draw.line((5,20,90,30),fill="black") #画线-----(开始坐标,结束坐标;颜色参数)
draw.line((10,20,50,30),fill="black")
draw.arc((60,0,68,8),0,90,fill="red") #画圆------(xxxxxxxxx)
draw.arc((0,0,80,40),0,90,fill="red")
font = ImageFont.truetype("blog/static/font/kumo.ttf",25)
# draw.text([20,10],"python","purple",font=font) #写文本 ----(坐标,文本,颜色,字体)
valid_list = []
for i in range(5):
'''文本信息'''
random_num = str(random.randint(0,9))
random_lower_char = chr(random.randint(65,90))
random_upper_char = chr(random.randint(97,122))
random_char = random.choice([random_num,random_lower_char,random_upper_char])
draw.text([5+i*24,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() #从内存取值
########################################################################3
valid_str = "".join(valid_list) #将列吧拼接成字符串
print(valid_str)
request.session["keepValidCode"]=valid_str #存到session中
return HttpResponse(data)