#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
import string
import random
from captcha.image import ImageCaptcha # 生成图像验证码
from io import BytesIO
from flask import Flask, make_response
str = string.ascii_letters +"3456789"
def get_captcha(str_length=4, width=160, height=50):
# 生成验证码str
text = "".join([random.choice(str) for _ in range(str_length)])
# 生成验证码图片
image = ImageCaptcha(width, height)
color = tuple([random.randint(0, 255)for _in range(3)])
background = tuple([random.randint(0, 255)for _in range(3)])
img = image.create_captcha_image(text, color=color, background=background)
# img.show()
# 将验证码保存到内存中
file = BytesIO()
img.save(file, format="JPEG")
return text, file.getvalue()
##################################################
app = Flask(__name__)
@app.route("/image_codes/<int:code_uuid>")
def get_image_code(code_uuid):
text, data = get_captcha(str_length=6)
print(text)
print(code_uuid)
print(data)
resp = make_response(data)
resp.headers["Content-Type"] = "image/jpg"
return resp
if __name__ =='__main__':
app.run(debug=True)