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

}
相关推荐
HySpark几秒前
ERes2Net声纹识别短音频匹配不稳定:从音频时长到有效音素的排查实践
python·语音识别·声纹识别·vad·eres2net
aibo8603081 分钟前
基于 Spring Boot + Vue3 的博物馆藏品管理系统设计与实现
java·spring boot·后端
TomEval3 分钟前
【测AI】第17篇:大模型评测方法论 —— LLM 怎么测?
人工智能·python·aigc·测试用例
苍何4 分钟前
Codex+Obsidian,多平台同步,一键分发,太香了!
后端
fanruitian5 分钟前
python 进程 线程
java·前端·python
zzu123zsw12 分钟前
把条件校验收敛到枚举接口:Spring Boot 统一断言模式与零污染异常切面工程化
java·spring boot·后端·架构设计
m0_敲代码的彭于晏16823 分钟前
OpenCode 2.0 智能编程效果全景展示
人工智能·python·语言模型
溪语流沙34 分钟前
【Web全栈进阶】监控与告警:线上系统的“体检报告”
前端·vue.js·python·fastapi
蜡笔羊驼43 分钟前
ModuleNotFoundError: No module named ‘torchvision.transforms.functional_tensor‘
linux·人工智能·python
李航19831 小时前
DeepDraw 网页版
人工智能·python·计算机视觉·ai·ai编程