Flask生成图片验证码的功能

1.将写好的包直接放入项目的utils文件夹中,注:安装 Pillow 时需要安装9.4.0;pip install Pillow==9.5.0 否则会报错

包的下载链接:infomation36: B站新闻管理系统项目,flask - Gitee.com

2.视图函数的完成
python 复制代码
from flask import request, current_app, make_response
from . import passport_blue
from ... import redis_store, constants
from ...utils.captcha.captcha import captcha


@passport_blue.route('/image_code')
def image_code():
    # 1. 获取前端传递过来的参数
    cur_id = request.args.get('cur_id')
    pre_id = request.args.get('pre_id')

    # 2. 调用captcha工具获取图片验证码,验证码的值,验证码图片(二进制)
    code_name, code_text, code_image = captcha.generate_captcha()

    # 3. 将图片验证码的值保存到redis中
    try:
        # 参数1:key,参数2:value,参数3:有效期
        redis_store.set("image_code:{}".format(cur_id), code_text, constants.IMAGE_CODE_REDIS_EXPIRES)

        # 4. 判断是否有上一次的图片验证码
        if pre_id:
            redis_store.delete('image_code:{}'.format(pre_id))
    except Exception as e:
        current_app.logger.error(e)
        return '图片验证码获取失败!'
    # 返回图片
    response = make_response(code_image)
    response.headers['Content-Type'] = 'image/png'
    return response
3. 前端的使用

---html部分:

html 复制代码
<img src="/passport/image_code" class="get_pic_code" onclick="generateImageCode()">

---js部分

javascript 复制代码
// TODO 生成一个图片验证码的编号,并设置页面中图片验证码img标签的src属性
function generateImageCode() {

    //1.生成一个随机字符串
    imageCodeId = generateUUID();

    //2.拼接图片url地址
    image_url = '/passport/image_code?cur_id=' + imageCodeId + "&pre_id=" + preimageCodeId

    //3.将地址设置到image标签的src属性中,为image_url
    $('.get_pic_code').attr('src', image_url)

    //4.记录上一次的编号
    preimageCodeId = imageCodeId

}
相关推荐
二十雨辰16 小时前
[python]-多任务
python
癫狂的兔子16 小时前
【Python】【机器学习】集成算法(随机森林、提升算法)
python·算法·机器学习
kong790692816 小时前
Python核心语法-Matplotlib简介
开发语言·python·matplotlib
马克Markorg16 小时前
基于LLM的大模型的RAG(检索增强生成)实现对比
python·大模型·agent·rag·企业级知识库的框架·rag 知识库
yy.y--17 小时前
Java线程实现浏览器实时时钟
java·linux·开发语言·前端·python
笨蛋不要掉眼泪17 小时前
Sentinel 流控规则详解:三种模式与三种效果实战指南
java·jvm·数据库·后端·sentinel
Dontla17 小时前
Python Streamlit介绍(开源Python Web应用框架,快速将Python脚本转换成交互式Web应用,适合数据科学和机器学习项目快速展示)
前端·python·开源
健康平安的活着17 小时前
AI之Toolcalling的使用案例(langchain4j+springboot)
人工智能·spring boot·后端
PythonFun17 小时前
HAProxy端口转发入门:从“搬砖工”到“智能交通警察”
服务器·后端·网络安全
少云清17 小时前
【UI自动化测试】12_web自动化测试 _验证码处理和cookie
前端·python·web自动化测试