django,flask生成图形验证码

一、生成图形验证码

1、生成图形验证码逻辑分析

在这里插入图片描述

  • 前端向后端申请图形验证码,通过uuid来区分身份
  • 后端生成图形验证码,并制作成验证码图片数据
  • 将图形验证码强果保存到redis中,以便后面验证
  • 将验证码图片数据传回前端进行展示

2操作简单直接上代码

首先将生成能生成图片的文件放入utils下的文件夹

 django,flask生成图形验证码_第1张图片

拉取画图文件:https://gitee.com/in-the-end-of-the-dream/project

3 django生成图片验证码

# 配置redis库
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://121.4.134.212:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "mysecret"
        }
    },
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://121.4.134.212:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "mysecret"
        }
    },
 # 验证码信息: 存到 2 号库
    "verify_code": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://:[email protected]:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"

4

#view
from django.shortcuts import render
from rest_framework.views import APIView
from App.utils.captcha.captcha import captcha
from App.utils.redis_utils import mredis
from rest_framework import response
from django.http import HttpResponse
from django_redis import get_redis_connection

# Create your views here.
class ImageCode(APIView):
    """图型验证码
    '''
        :param request:
        :param uuid:  通用唯一识别符,用于标识唯一图片验证码属于哪个用户的
        :return:  image/jpg
        '''
    """
    def get(self,request,uuid):
        # 路由传参
        # 调用captch外部库生成图片和验证码
        name, text, img = captcha.generate_captcha()
        # 3.2、把验证码写入redis(以uuid作为key)
        # get_redis_connection函数:功能是获取redis链接对象,参数是一个字符串(是django缓存配置名称)
        # 返回值是一个redis链接对象
        conn = get_redis_connection('verify_code')
        # setex img_37728d6c-e219-44c5-8f81-4245a9e557a4 300 KJHG
        conn.setex('img_%s' % uuid, 60*3, text)
        # 4、构建响应(返回图片数据)
        # 构造的响应体数据是图片的二进制字节数据,需要设置响应头Content-Type:image/jpeg,来
        # 告诉浏览器响应体数据是图片数据,这样浏览器才能够渲染图片
        return HttpResponse(img, content_type='image/png')

#url
from django.contrib import admin
from django.urls import path,include
from App.views import ImageCode

urlpatterns = [
    path('image//',ImageCode.as_view())
]

flask生成图片验证码

先拉入画图文件

django,flask生成图形验证码_第2张图片

from flask import make_response
from common.utils.captcha import Captcha
from io import BytesIO
from common.settings.default import rds


def graph_captcha(uuid):
    text, image = Captcha.gene_graph_captcha()
    print(type(text),image)
    rds.setex(uuid, 60 * 5, text)
    out = BytesIO()
    image.save(out, 'png')
    out.seek(0)
    resp = make_response(out.read())
    resp.content_type = 'image/png'
    return resp
图形验证码的封装
import functools
from flask import Blueprint, request
from flask_restful import reqparse

from common.utils.code_utils import graph_captcha

verification_bp = Blueprint('verification_bp', __name__)


def decorate(func):
    """图像验证码封装"""
    @functools.wraps(func)
    def inner():
        uuid = request.args.get('uuid')
        if not uuid:
            return {'message': 'uuid not existed'}
        resp = graph_captcha(uuid)
        print(resp)
        # return resp
        return func(resp)

    return inner


@verification_bp.route('/code')
@decorate
def verification(resp):
    """生成图像验证码"""
    return resp
import traceback
import logging

from flask import Blueprint
from flask_restful import Resource, Api, reqparse, marshal
from common.utils.custom_output_json import custom_output_json
from common.utils.jwt_util import _generate_token
from common.models.zixun_model import *
from common.models_fields.user_fields import user_fields2
from common.settings.default import rds
from common.utils.phone import send_message
from sqlalchemy import or_, and_
from common.celery_task.main import add

user_bp = Blueprint('user_bp', __name__)
api = Api(user_bp)
#生成图片验证码
# class VerificationCode(Resource):
#     def get(self):
#         try:
#             parser = reqparse.RequestParser()
#             parser.add_argument('uuid')
#             args = parser.parse_args()
#             uuid = args.get('uuid')
#             # uuid = request.args.get('uuid')
#             if not uuid:
#                 return {'message': 'uuid not existed'}
#             resp = graph_captcha(uuid)
#             # print(resp)
#             return resp
#         except:
#             error = traceback.format_exc()
#             logging.error('code image error{}'.format(error))
#             return 'fail'

vue2前端





import {v4 as uuidv4} from 'uuid'




  methods: {
    getCaptcha() {

    //   this.axios.get("image/"+this.uuidv4+'/').then((res) => {
    //     console.log(res);
    //     this.captchaImg = res.data;
    //   });
	this.uuid = uuidv4()
	console.log(this.uuid)
	  this.image_code_url =this.axios.defaults.baseURL+ "image/"+this.uuid+'/'
	  console.log(this.image_code_url)
    },
  },
  mounted() {
    this.getCaptcha();
  },

1.安装uuid

代码如下(示例):

npm install -S uuid
  • 1

2.在需要使用uuid的.vue文件中生成uuid

代码如下(示例):

import { v4 as uuidv4 } from 'uuid';


sid=uuidv4()

你可能感兴趣的:(flask,python,后端)