pip install pillowvIEws.py 生成验证码
from flask import render_template,request,redirect,url_for,session,make_responsefrom PIL import Image,ImageFont,ImageDraw,ImageFilterfrom io import BytesIOdef 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)),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# restfulfrom flask_restful import APIauther = Blueprint(‘auther‘,__name__)# 注册restfulrestfulAPI = API(auther)# 注意蓝图在__init__.py文件中 必须导入vIEws视图from . import vIEwsmodel.py
#!/usr/bin/env python3# -*- Coding: utf-8 -*-#from app import db,login_managerfrom werkzeug.security import generate_password_hash,check_password_hashfrom flask_login import UserMixinclass 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_loaderdef load_user(user_ID): return User.query.get(int(user_ID))HTML login.HTML
{% extends ‘authentication/base.HTML‘ %}{% block Title %} 登入 - 黑熊平台 {% endblock %}{% block content %} <div ID="LAY-user-login" > <div > <div > <h2>黑熊平台</h2> <p>后台管理系统</p> </div> <div > <div > <label for="LAY-user-login-username"></label> <input type="text" name="name" ID="LAY-user-login-username" lay-verify="required" placeholder="用户名" > </div> <div > <label for="LAY-user-login-password"></label> <input type="password" name="password" ID="LAY-user-login-password" lay-verify="required" placeholder="密码" > </div> <div > <div > <div > <label for="LAY-user-login-vercode"></label> <input type="text" name="vercode" ID="LAY-user-login-vercode" lay-verify="required" placeholder="图形验证码" > </div> <div > <div > <img src="{{ url_for(‘auther.valIDate_code‘) }}" ID="valIDate"> </div> </div> </div> </div> <div > <button lay-submit lay-filter="LAY-user-login-submit">登 入</button> </div> <div > <label>预留</label> <a href="JavaScript:;"><i ></i></a> <a href="JavaScript:;"><i ></i></a> <a href="JavaScript:;"><i ></i></a> <a href="{{ url_for(‘auther.register‘) }}" >注册帐号</a> </div> </div> </div> </div>{% endblock %}{% block script %} {{ super() }} <script> // 加载模块 form layui.use(‘form‘,function () { var form = layui.form; form.render(); // 更新全部 form.on(‘submit(LAY-user-login-submit)‘,function (obj) { var fIEld = obj.fIEld; $.AJAX({ url: ‘{{ url_for("auther.login") }}‘,type: "post",data: fIEld,success: function (data) { if (data.code == 10000) { window.open(data.url,‘__self‘); } else if (data.code == 10001) { layer.msg(‘帐号或密码错误,请重新输入‘,{icon: 5}) } else if (data.code == 10002) { layer.msg(‘帐户未被激活,请联系管理员激活‘,{icon: 5}) } else if (data.code == 10003){ layer.msg(‘验证码不正确,请重新输入‘,{icon: 5}) } } }) }) }) $("#valIDate").on(‘click‘,function () { $.AJAX({ url: ‘{{ url_for("auther.valIDate_code") }}‘,type:"get",success: function (data) { $("#valIDate").attr(‘src‘,"{{ url_for(‘auther.valIDate_code‘) }}") } }) }) </script>{% endblock %}base.HTML
<!DOCTYPE HTML><HTML><head> <Meta charset="utf-8"> <Title>{% block Title %} {% endblock %}</Title> <Meta name="renderer" content="webkit"> <Meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1"> <Meta name="vIEwport" content="wIDth=device-wIDth,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0"> <link rel="stylesheet" href="/static/layui/CSS/layui.CSS" media="all"> <link rel="stylesheet" href="/static/layui/CSS/admin.CSS" media="all"> <link rel="stylesheet" href="/static/layui/CSS/login.CSS" media="all"></head><body>{% block content %}{% endblock %}{% block script %} <script src="/static/Js/jquery-3.4.1.Js"></script> <script src="/static/layui/layui.Js"></script>{% endblock %}</body></HTML>
点击登入,查看后台session
每次点击之后 点登入 session image值就会更改 <RedisSession {‘_permanent‘: True,‘image‘: ‘29r0i‘,<RedisSession {‘_permanent‘: True,‘image‘: ‘n8091‘,检验 总结
以上是内存溢出为你收集整理的flask中使用验证码全部内容,希望文章能够帮你解决flask中使用验证码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)