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
python中图像验证码的实现
最新推荐文章于 2024-04-27 03:20:48 发布