记录纯粹通过Python Flask生成并显示验证码,实现用户验证登录。实现过程中我参考了大量相关教程和笔记,感谢为之分享的各位!

目前对此的理解不是很深刻,先附上实现的过程

一.Flask后端

要实现验证码,需要用到PIL库生成验证码图片 ,Python3输入如下命令安装

  • pip install pillow

下载ttf格式字体,放在程序根目录,然后用以下函数实现验证码生成


from PIL import Image, ImageDraw, ImageFont, ImageFilter 
from io import BytesIO
import random
import base64
#验证码图片
 def validate_picture():
 total = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789’
 # 图片大小130 x 50
 width = 130
 heighth = 50
 # 先生成一个新图片对象
 im = Image.new(‘RGB’,(width, heighth), ‘white’)
 # 设置字体, MicrosoftYaqiHeiLight-2.ttf是我下载的字体,放在程序根目录
 font = ImageFont.truetype(“MicrosoftYaqiHeiLight-2.ttf”, 30)
 # 创建draw对象
 draw = ImageDraw.Draw(im)
 str = ‘’
 # 输出每一个文字
 for item in range(4):
 text = random.choice(total)
 str += text
 draw.text((-3+random.randint(3,7)+25*item, -3+random.randint(2,7)), text=text, fill=‘black’,font=font )
# 划几根干扰线
for num in range(1):
    x1 = random.randint(0, width/2)
    y1 = random.randint(0, heighth/2)
    x2 = random.randint(0, width)
    y2 = random.randint(heighth/2, heighth)
    draw.line(((x1, y1),(x2,y2)), fill='black', width=1)

# 加上滤镜
im = im.filter(ImageFilter.FIND_EDGES)
return im, str
#生成验证码实例的函数
 def run_code():
 #生成验证码,image为验证码图片,code为验证码文本
 image, code = validate_picture()
# 将验证码图片以二进制形式写入在内存中,防止将图片都放在文件夹中,占用大量磁盘
buf = BytesIO()
image.save(buf, 'jpeg')
buf_str = buf.getvalue()


data = str(base64.b64encode(buf_str))[1:].strip("'")    #将验证码转换为base64格式
# session['code'] = code  #现在暂时未打开,将验证码文本存入session,做用户登录认证时可用
return data</code></pre>

 

完整的py程序为

 


from flask import Flask
from flask import render_template
from PIL import Image, ImageDraw, ImageFont, ImageFilter 
from io import BytesIO
import random
 import base64#验证码图片
 def validate_picture():
 total = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789’
 # 图片大小130 x 50
 width = 130
 heighth = 50
 # 先生成一个新图片对象
 im = Image.new(‘RGB’,(width, heighth), ‘white’)
 # 设置字体
 font = ImageFont.truetype(“MicrosoftYaqiHeiLight-2.ttf”, 30)
 # 创建draw对象
 draw = ImageDraw.Draw(im)
 str = ‘’
 # 输出每一个文字
 for item in range(4):
 text = random.choice(total)
 str += text
 draw.text((-3+random.randint(3,7)+25*item, -3+random.randint(2,7)), text=text, fill=‘black’,font=font )
# 划几根干扰线
for num in range(1):
    x1 = random.randint(0, width/2)
    y1 = random.randint(0, heighth/2)
    x2 = random.randint(0, width)
    y2 = random.randint(heighth/2, heighth)
    draw.line(((x1, y1),(x2,y2)), fill='black', width=1)

# 加上滤镜
im = im.filter(ImageFilter.FIND_EDGES)
return im, str
#生成验证码实例的函数
 def run_code():
 #生成验证码,image为验证码图片,code为验证码文本
 image, code = validate_picture()
# 将验证码图片以二进制形式写入在内存中,防止将图片都放在文件夹中,占用大量磁盘
buf = BytesIO()
image.save(buf, 'jpeg')
buf_str = buf.getvalue()


data = str(base64.b64encode(buf_str))[1:].strip("'")    #将验证码转换为base64格式
# session['code'] = code  #将验证码文本存入session,做用户登录认证时可用
return data
app = Flask(name)
@app.route(’/’)
 def test():
 data = run_code() #生成新验证码
 return render_template(‘test.html’, img_stream = data) #会在下面贴出我的html源码if name == ‘main’:
 app.run(host=‘0.0.0.0’, debug=True)

 

二.HTML模板

Flask中创建如下html模板,放在 程序根目录/templates 中




 



之后运行Python,打开浏览器输入地址,便能成功显示验证码了,每次刷新自动生成哦

python flask该端口_flask

如果您有更好的方法,欢迎留言哦