(编辑:jimmy 日期: 2024/11/16 浏览:2)
本文实例讲述了Django框架验证码用法。分享给大家供大家参考,具体如下:
验证码
1、作用
2、业务流程
绘制验证码图片
background = (10,20,30) // RGB颜色
初始化画布
image = Image.new(‘RGB',(100,50),background)
获取画布中画笔对象
draw = ImageDraw.Draw(image)
绘制验证码,随机四个
font = ImageFont.truetype(‘path',size) fontcolor = (20,40,60) draw.text((x,y),'R',font,fontcolor)
返回验证码内容
# 删除画笔 del draw #保存图片到BytesIO对象 Import io buf = io.BytesIO() image.save(buf,'png') #返回BytesIO中的内容 return HttpResponse(buf.getvalue(),'image/png')
3、代码范例
html页面
<form method="post" action="{% url 'sitesApp:login' %}"> {% csrf_token %} <div class="login"> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">用户名</span> <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1" name="uName"> </div> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">密 码</span> <input type="text" class="form-control" placeholder="Password" aria-describedby="basic-addon1" name="uPswd"> </div> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">验证码</span> <input type="text" class="form-control" placeholder="Auth code" aria-describedby="basic-addon1" name="uCode"> </div> <div class="vcode"> <img src="/UploadFiles/2021-04-08/">views视图
''' 生成并返回验证码 ''' def getvcode(request): # 随机生成验证码 population = string.ascii_letters+string.digits letterlist = random.sample(population,4) vcode = ''.join(letterlist) # 保存该用户的验证码 request.session['vcode']=vcode # 绘制验证码 # 需要画布,长宽颜色 image = Image.new('RGB',(176,60),color=getRandomColor()) # 创建画布的画笔 draw = ImageDraw.Draw(image) # 绘制文字,字体所在位置 path = os.path.join(BASE_DIR,'static','fonts','ADOBEARABIC-BOLDITALIC.OTF') font = ImageFont.truetype(path,50) for i in range(len(vcode)): draw.text((20+40*i,0),vcode[i],fill=getRandomColor(),font=font) # 添加噪声 for i in range(500): position = (random.randint(0,176),random.randint(0,50)) draw.point(position,fill=getRandomColor()) # 返回验证码字节数据 # 创建字节容器 buffer = io.BytesIO() # 将画布内容丢入容器 image.save(buffer,'png') # 返回容器内的字节 return HttpResponse(buffer.getvalue(),'image/png') # 获取随机颜色 def getRandomColor(): red = random.randint(0,255) green = random.randint(0,255) blue = random.randint(0,255) return (red,green,blue)希望本文所述对大家基于Django框架的Python程序设计有所帮助。