图片检验码, web框架用的是layui

安装

  pip install pillow

flask中使用验证码_第1张图片

views.py

生成验证码

from flask import render_template, request, redirect, url_for, session, make_response
from PIL import Image, ImageFont, ImageDraw, ImageFilter
from io import BytesIO

def validate_picture(width=130, heigth=50):
    # 生成一个临时随机的字符串
    nonce = ''.join([random.choice([chr(random.randrange(97, 122)), str(random.randint(0, 9)),
                                    chr(random.randrange(65, 90))]) for i in range(5)])
    # 生成一个图片对象    颜色, (宽,高), 颜色 三色随机
    imgobj = Image.new('RGB', (width, heigth), color=tuple([random.randint(0, 255) for i in range(3)]))
    draw = ImageDraw.Draw(imgobj)   # 创建draw对象

    font = ImageFont.truetype('/static/font/msyh.ttf', size=30)  # 设置字体, 字体大小
    draw.text((10, 4), text=nonce, fill='black', font=font)  # 用画笔在板子上画出来,

    # 划几根干扰线
    for num in range(8):
        x1 = random.randint(0, width / 2)
        y1 = random.randint(0, heigth / 2)
        x2 = random.randint(0, width)
        y2 = random.randint(heigth / 2, heigth)
        draw.line(((x1, y1), (x2, y2)), fill='black', width=1)

    # 模糊下,加个帅帅的滤镜~
    im = imgobj.filter(ImageFilter.FIND_EDGES)
    return im, nonce

@auther.route('/validate_code')
def validate_code():
    image, nonce = validate_picture()
    buf = BytesIO()
    image.save(buf, 'jpeg')
    # 读取写入后的二进制文件
    data = buf.getvalue()
    # 把二进制作为response发回前端,并设置首部字段
    response = make_response(data)
    response.headers['Content-Type'] = 'image/jpeg'
    # 添加session, 在session中在次进行判断
    session['image'] = nonce
    return response

登陆类

# 主页
@auther.route('/')
def loginindex():
    return render_template('authentication/login.html')

class Login(Resource):
    def post(self):
        '''
            状态码  10000: 表示已激活 可以登陆
                    10001:  帐号或密码错误
                    10002: 没有激活
                    10003: 验证码不对
        # 1、检查用户是否存在
        # 2、检查用户是否激活,没有就直接 return
        # 3、如果正常返回url
        '''
        print(session)
        res = {'code': 10001}  # 直接判断不存在
        logdic = request.form.to_dict()  # 获取字典
        username = User.query.filter_by(name=logdic["name"]).first()
        if username:
            if username.is_active:
                if session.get('image'):
                                # 不区分大小写
                    if session.get('image').lower() != logdic["vercode"].lower():
                        res["code"] = 10003
                if username.verify_password(logdic["password"]):
                    login_user(username)
                    session['name'] = logdic['name']
                    res["url"] = request.args.get('next') or url_for("backend.index")
                    res["code"] = 10000
            else:
                res["code"] = 10002
        return res

__init__.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 蓝图
from flask import Blueprint
# restful
from flask_restful import Api
auther = Blueprint('auther',__name__)
# 注册restful
restfulApi = Api(auther)
# 注意蓝图在__init__.py文件中 必须导入views视图
from . import views

model.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#

from app import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    email = db.Column(db.String(40), unique=True, nullable=True)
    password_hash = db.Column(db.String(128))
    is_active = db.Column(db.Boolean, default=False)

    @property
    def password(self):
        raise AttributeError("输入错误")

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

# 加载用户回调函数
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

html

login.html

{% extends 'authentication/base.html' %}
{% block title %} 登入 - 黑熊平台 {% endblock %}

{% block content %}
    
{% endblock %}

{% block script %}

    {{ super() }}
    
{% endblock %}

base.html




    
    {% block title %} {% endblock %}
    
    
    
    
    
    


{% block content %}
{% endblock %}

{% block script %}
    
    
{% endblock %}

flask中使用验证码_第2张图片

点击登入,查看后台session

  每次点击之后 点登入 session  image值就会更改
    

检验

flask中使用验证码_第3张图片