目录
一、逻辑分析
要点
- 将图形验证码的文字信息保存到Redis数据库,为短信验证码做准备。
- UUID 用于唯一区分该图形验证码属于哪个用户,也可使用其他唯一标识信息来实现
二、接口设计和定义
2.1 图形验证码接口设计
1. 请求方式
选项 方案 请求方法 GET 请求地址 image_codes/(?P<uuid>[\w-]+)/
2. 请求参数:路径参数
参数名 类型 是否必传 说明 uuid string 是 唯一编号
3. 响应结果:
image/jpg
2.2 图形验证码接口定义
新建一个用于验证的子应用 verifications
python3 ../../manage.py startapp verifications
1. 图形验证码视图
class ImageCodeView(View): """图形验证码""" def get(self, request, uuid): """ :param request: 请求对象 :param uuid: 唯一标识图形验证码所属于的用户 :return: image/jpg """ pass
2. 总路由添加
# 验证码 path('', include('verifications.urls')),
3. verifications下添加子路由urls.py
from django.conf.urls import url from . import views urlpatterns = [ # 图形验证码 url(r'^image_codes/(?P<uuid>[\w-]+)/$', views.ImageCodeView.as_view()) ]
三、后端逻辑
3.1 verifications下创建一个依赖包,将captcha扩展包粘贴进来
提示:
captcha
扩展包用于后端生成图形验证码
可能出现如下报错,原因:环境中没有Python处理图片的库:PIL
解决办法:安装Python处理图片的库
pip install Pillow
3.2 准备Redis数据库
配置文件 dev.py 中 CACHES 添加 Redis的2号库存储验证码数据
# 验证码 "verify_code": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://:123456@192.168.2.105:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } },
3.3 图形验证码后端逻辑实现
verifications\views.py
from django.shortcuts import render from django.views import View from django_redis import get_redis_connection from django import http from . import constants from verifications.libs.captcha.captcha import captcha class ImageCodeView(View): """图形验证码""" def get(self, request, uuid): """ :param uuid: 通用唯一识别码,用于唯一标识该图形验证码属于哪个用户的 :return: image/jpg """ # 实现主体业务逻辑:生成,保存,响应图形验证码 # 生成图形验证码 text, image = captcha.generate_captcha() # 保存图形验证码 redis_conn = get_redis_connection('verify_code') # redis_conn.setex('key', 'expires', 'value') redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text) # 响应图形验证码 return http.HttpResponse(image, content_type='image/jpg')
四、前端逻辑
4.1 Vue实现图形验证码展示 与 校验
1. register.js
// 页面加载完会被调用的 mounted() { // 生成图形验证码 this.generate_image_code(); }, methods: { // 生成图形验证码的方法:封装的思想,代码复用 generate_image_code() { this.uuid = generateUUID(); this.image_code_url = '/image_codes/' + this.uuid + '/'; }, // 校验图形验证码 check_image_code() { if (this.image_code.length != 4) { this.error_image_code_message = '请输入图形验证码'; this.error_image_code = true; } else { this.error_image_code = false; } }, }
2. register.html
<li> <label>图形验证码:</label> <input type="text" v-model="image_code" @blur="check_image_code" name="image_code" id="pic_code" class="msg_input"> <img :src="image_code_url" @click="generate_image_code" alt="图形验证码" class="pic_code"> <span class="error_tip" v-show="error_image_code">[[ error_image_code_message ]]</span> </li>
3. 界面展示
redis存储