python中图像验证码的实现

from flask import current_app, jsonify
from flask import make_response
from flask import request

from info import constants
from info import redis_store
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blu


@passport_blue.route('/image_code')
def get_image_code():
    """
    获取图片验证码
    :return:
    """
    # 1. 获取参数 --> 目的是为了保存. 没有数据就无法保存
    image_code_id = request.args.get('image_code_id')
    if not image_code_id:
        return abort(403)

    # 2. 生成图片验证码 --> 网上有很多写好的工具
    name, text, image_data = captcha.generate_captcha()

    # 3. 保存到redis中
    # setex: Key, 时间, value
    try:
        # 可以给redis_store增加类型注释, 来获得智能提示
        # 在info/__init__文件中: redis_store = None  # type: redis.StrictRedis
        redis_store.setex('image_code_id_' + image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        # 3.1 日志记录错误
        logging.error(e)
        # 3.2 返回错误
        return abort(500)

    # 4. 返回给浏览器
    response = make_response(image_data)
    response.headers['Content-Type'] = 'image/jpg'
    return response
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值