# -*- coding:utf-8 -*-
"""
@Author :摘星造梦
@Time : 14:23
"""
import io
import random
import secrets
import string
from flask import Flask, render_template, request, redirect, url_for, session, jsonify
from PIL import Image
from PIL import ImageDraw, ImageFont
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
app.secret_key = secrets.token_hex(16)
@app.route('/index')
def index():
return jsonify({'data':'首页'})
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
data = request.get_json()
username = data['username']
password = data['password']
code = data['code']
if username == 'admin' and password == '123' and code == session['captcha']:
return jsonify({'status':'success'}), 200
else:
return jsonify({'status':False, 'message':'用户名/密码/验证码错误'})
return jsonify({'status':False, 'message':'请求方法错误'})
@app.route('/captcha', methods=['GET', 'POST'])
def captcha():
# 生成一个图片
image = Image.new('RGB', (120, 30), color=(73, 109, 137))
# 字体
font_path = 'C:\Windows\Fonts\Arial.ttf'
# 创建一个绘画对象,用于在图像上绘制文本和图形
fnt = ImageFont.truetype(font_path, 15)
d = ImageDraw.Draw(image)
# 随机从大写字母和数字里选4个字符做验证码
captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
# 在图像上绘制验证码文本
d.text((10, 10), captcha_text, font=fnt, fill=(255, 255, 0))
# 添加干扰线条
for _ in range(random.randint(3, 5)):
'''添加3到5条干扰线'''
# 线条起始点和结束点坐标
start = (random.randint(0, image.width), random.randint(0, image.height))
end = (random.randint(0, image.width), random.randint(0, image.height))
d.line([start, end], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# 添加噪点
for _ in range(100):
'''添加100个噪点'''
# 随机生成噪点坐标
xy = (random.randrange(0, image.width), random.randrange(0, image.height))
# 绘制噪点
d.point((xy, xy), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# 将生成的验证码存储到会话中
session['captcha'] = captcha_text
# 创建一个字节流对象 保存图像数据
buf = io.BytesIO()
image.save(buf, 'PNG')
# 将字节流的指针移动到开头
buf.seek(0)
# 返回字节流中的图像数据,状态码200,并设置响应头
return buf.getvalue(), 200, {
'Content-Type': 'image/png',
'Content-Length': str(len(buf.getvalue()))
}
app.run(debug=True)