注册功能实现 -- 3.图片验证码接口实现

图片验证码

1. 分析

前端发送图片uuid,后端生成图片,返回前端

2. 请求方式

request: GET

3. 接口URL路径定义

url: /captcha_codes//

4. 前端传递参数方式及数据格式

传递参数方式:url 路径参数传参

参数 类型 前端是否必须传 描述
captcha_uuid uuid字符串 图片验证码编号

uuid:Universally unique identifier(eg. 123e4567-e89b-12d3-a456-426655440000)

5.代码实现
  • 后端代码
    • 配置 verifications app
      • 生成 manage.py@Dreamblog > startapp verifications
      manage.py@Dreamblog > startapp verifications
      
      • 注册
      INSTALLED_APPS = [
      # ...
      'verifications',
      ]
      
      • 导入路径
      urlpatterns = [
      # ...
      path('verifications/', include('verifications.urls')),
      ]
      
    • 将 图像验证码的模块文件夹(captcha文件夹)复制粘贴到项目根目录utils文件夹下
    • 安装图片验证码所需要的 Pillow 模块 pip install Pillow
    • 确保settings.py文件中有配置redis CACHE
      Redis原生指令参考 http://redisdoc.com/index.html
      Redis python客户端 方法参考 http://redis-py.readthedocs.io/en/latest/#indices-and-tables
    # 配置redis缓存
    # 在settings.py文件中指定redis配置
    CACHES = {
        # 默认redis数据库 -- default
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",  # 引擎
            "LOCATION": "redis://127.0.0.1:6379/0",  # 0 代表第一个数据库,端口默认6379
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        },
    
        # 指定redis数据库 -- "verify_codes"
        # 保存图片以及短信验证码
        "verify_codes": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379/1",  # 1 代表第一个数据库,
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        },
      }
    
    • 代码实现
# views.py
import logging


from django.views import View
from django.http import HttpResponse
from django_redis import get_redis_connection


from . import constants
from utils.captcha.captcha import captcha


logger =logging.getLogger('django')

# 图片验证码视图
class CaptchaView(View):
    """
    1.创建一个类视图: CaptchaView
    2.明确请求方式:   GET
    3.url路径定义:    /captcha_codes//
    4.前端传参方式及参数:
        -- 传参方式:  url路径传参,
        -- 参数:      captcha_uuid
    5.获取前端参数:
        -- get(self, request, captcha_uuid)
    6.业务处理:
        -- 1.是否需要校验以及校验方式   不需要,url路径传参已校验
        -- 2.是否需要储存以及储存方式   需要,redis储存
        -- 3.其他                      利用uuid生成图片验证码
    7.返回前端参数:
        -- return HttpResponse(content=captcha_content, content_type='image/jpg')
    """
    def get(self, request, captcha_uuid):
        """

        :param request:
        :param captcha_uuid:
        :return:
        """
        # 利用接口,生成图片验证码文本以及二进制文件
        captcha_text, captcha_content = captcha.generate_captcha()

        # redis 保存数据三部曲
        # 1. 连接redis
        conn_redis = get_redis_connection(alias="verify_codes")
        # 2. 建立key值    -- key值设为二进制
        captcha_key = 'captcha_{}'.format(captcha_uuid).encode('utf-8')
        # 3. 保存数据,并设置有效期
        conn_redis.setex(captcha_key, constants.CAPTCHA_CODE_REDIS_EXPIRES, captcha_text)

        # 日志器记录,后台显示
        logger.info('图片验证码为:{}'.format(captcha_text))

        # 返回前端参数,验证码二进制文件
        # type='image/jpg'默认打开, type='images/jpg'默认下载
        return HttpResponse(content=captcha_content, content_type='image/jpg')


# constants.py
# 图片验证码redis有效期,单位秒
CAPTCHA_CODE_REDIS_EXPIRES = 5 * 60
  # urls.py
  from django.urls import path
  from . import views

  app_name = 'verifications'

  urlpatterns = [
      path('captcha_codes//', views.CaptchaView.as_view(),   name='captcha_code'),
  ]
  • postman测试


    image.png
  • redis数据库查看数据

127.0.0.1:6379[1]> keys *
(empty list or set)
127.0.0.1:6379[1]> keys *
1) "captcha_123e4567-e89b-12d3-a456-426655440000"
127.0.0.1:6379[1]> ttl "captcha_123e4567-e89b-12d3-a456-426655440000"
(integer) 183
127.0.0.1:6379[1]> 

6.前端代码

register.html代码


 

 
{% block script %}
  
{% endblock %}

在js文件夹下创建一个users文件夹用户存放用户模块相关的js文件,在users文件下创建users.js文件

// -----------------register.js--------------------- //
$(function () {
// -----------------图像验证码逻辑代码--------------------- //

   let $captcha = $('.captcha_image');  // 获取图像标签
   let s_UUID = '';                     // 定义图像验证码ID值
   let s_captcha_url= '';               // 定义获取图像验证码 url

    // 生成图像验证码图片
  generateImageCode();

    // 点击图片验证码生成新的图片验证码图片
  $captcha.click(generateImageCode);

    // 生成请求验证码 url
  function generateImageCode() {
    // 1、生成一个图片验证码随机编号
    s_UUID = generateUUID();
    // 2、拼接请求url  verifications/captcha_codes//
    s_captcha_url = '/verifications/captcha_codes/' + s_UUID + '/';
    // 3、修改验证码图片src地址(此时后端传入图片二进制,显示)
    $captcha.attr('src',s_captcha_url)

  }

    // 生成图片UUID验证码
  function generateUUID() {
    let d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
  }
});

展示


image_1.png

image_2.png
127.0.0.1:6379[1]> keys *
1) "captcha_9cdb9550-b409-4dc9-aa35-52b865f19108"
2) "captcha_fcb8934b-8086-48f2-a712-de1b9b1ab516"
3) "captcha_034ea509-5423-4d9d-a074-e996366af401"
4) "captcha_09aef28e-22ef-4587-b37a-77acb4376a57"
5) "captcha_85b481da-f926-4182-b474-7c2324be351f"
6) "captcha_d58f4beb-a9a3-4e8b-8c4f-979c7a96acea"
7) "captcha_abf202b8-63f8-4e68-b3af-5f234c2c7342"

你可能感兴趣的:(注册功能实现 -- 3.图片验证码接口实现)