flask 验证码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jacke121/article/details/88050700

flask 验证码

 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41376740/article/details/79464805

前景

在学习flask web 开发的过程中,终于到了登录注册的界面,之前用PIL制作了自己的验证码,现在终于用上了,在搜集各种资料的情况下。终于初步完成了flask的验证码环节

验证码代码

from PIL import Image, ImageFont, ImageDraw, ImageFilter
import random


def validate_picture():
    total = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789'
    # 图片大小130 x 50
    width = 130
    heighth = 50
    # 先生成一个新图片对象
    im = Image.new('RGB',(width, heighth), 'white')
    # 设置字体
    font = ImageFont.truetype('FreeSans', 40)
    # 创建draw对象
    draw = ImageDraw.Draw(im)
    str = ''
    # 输出每一个文字
    for item in range(5):
        text = random.choice(total)
        str += text
        draw.text((5+random.randint(4,7)+20*item,5+random.randint(3,7)), text=text, fill='black',font=font )

    # 划几根干扰线
    for num in range(8):
        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

我选择用一个单独的文件写了一个验证码,这个函数返回im对象和验证码构成的字符串

forms.py

class LoginForm(FlaskForm):
    email = StringField('电子邮箱', validators=[DataRequired(), Length(1, 64), Email()])
    password = PasswordField('密码', validators=[DataRequired()])
    verify_code = StringField('验证码', validators=[DataRequired()])
    remember_me = BooleanField('记住自己的用户')
    submit = SubmitField('登录')
views.py
@auth.route('/code')
def get_code():
    image, str = validate_picture()
    # 将验证码图片以二进制形式写入在内存中,防止将图片都放在文件夹中,占用大量磁盘
    buf = BytesIO()
    image.save(buf, 'jpeg')
    buf_str = buf.getvalue()
    # 把二进制作为response发回前端,并设置首部字段
    response = make_response(buf_str)
    response.headers['Content-Type'] = 'image/gif'
    # 将验证码字符串储存在session中
    session['image'] = str
    return response
@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if session.get('image') != form.verify_code.data:
            flash('验证码错误')
        # 验证用户的登录密码
        if user is not None and user.verify_password(form.password.data):
            login_user(user,form.remember_me.data)
            flash('验证通过,登录成功')
            return redirect(request.args.get('next') or 
            url_for('main.index'))
        else:
            flash('用户名或者密码不正确')
    return render_template('auth/login.html',form=form)

login.html

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky - Login{% endblock %}
{% block page_content %}
<div class="page-header">
    <h1>Login</h1>
</div>
<div class="col-md-4">
    {{ wtf.quick_form(form) }}
    <!--点击图片重新获取验证码-->
    <img  src="/auth/code " onclick="this.src='/auth/code?'+ Math.random()">
</div>
{% endblock %}

实验结果

登录界面: 
这里写图片描述 
response返回的注册码图片: 

查看一个头部信息:content-type为image/gif 
这里写图片描述 
同样,点击之后是会刷新验证码

猜你喜欢

转载自blog.csdn.net/jacke121/article/details/88050700