一、图形验证码
1.1 图形验证码逻辑分析
需要新建应用verifications
- 将图形验证码的文字信息保存到Redis数据库,为短信验证码做准备。
- UUID 用于唯一区分该图形验证码属于哪个用户,也可使用其他唯一标识信息来实现。
1.请求方式
选项方案请求方法GET请求地址image_codes/(?P[\w-]+)/2.请求参数:路径参数
参数名类型是否必传说明uuidstring是唯一编号3.响应结果:image/jpg
1.图形验证码视图
views.py
from django.shortcuts import render
from django.views import View
# Create your views here.
class ImageCodeView(View):
"""图形验证码"""
def get(self, request, uuid):
"""
:param request:请求对象
:param uuid: 唯一标识图形验证码所属于的用户
:return: image/jpg
"""
pass
2.总路由
# verifications
url(r'^', include('verifications.urls')),
3.子路由
from django.conf.urls import url
from . import views
urlpatterns = [
# 图形验证码
url(r'^image_codes/(?P[\w-]+)/$', views.ImageCodeView.as_view()),
]
1.3 图形验证码后端逻辑
1. 准备captcha扩展包
提示:captcha
扩展包用于后端生成图形验证码
可能出现的错误
- 报错原因:环境中没有Python处理图片的库:PIL
解决办法
- 安装Python处理图片的库:
pip install Pillow
准备Redis的2号库存储验证码数据(setting.py)
"verify_code": { # 验证码
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
3. 图形验证码后端逻辑实现
from django.shortcuts import render
from django.views import View
from .lib.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
from meiduo_mall.meiduo_mall.utils import constants
# Create your views here.
class ImageCodeView(View):
"""图形验证码"""
def get(self, request, uuid):
"""
:param request:请求对象
:param uuid: 唯一标识图形验证码所属于的用户
:return: image/jpg
"""
# 生成图片验证码
text, image = captcha.generate_captcha()
# 保存图片验证码
redis_conn = get_redis_connection('verify_code')
redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)
# 响应图片验证码
return http.HttpResponse(image, constant_tpye='image/jpg')
1.register.js
mounted(){
// 生成图形验证码
this.generate_image_code();
},
methods: {
// 生成图形验证码
generate_image_code(){
// 生成UUID。generateUUID() : 封装在common.js文件中,需要提前引入
this.uuid = generateUUID();
// 拼接图形验证码请求地址
this.image_code_url = "/image_codes/" + this.uuid + "/";
},
......
}
2.register.html
图形验证码:
请填写图形验证码
3.图形验证码展示和存储效果
1.register.html
图形验证码:
[[ error_image_code_message ]]
2.register.js
check_image_code(){
if(!this.image_code) {
this.error_image_code_message = '请填写图片验证码';
this.error_image_code = true;
} else {
this.error_image_code = false;
}
},
3.图形验证码校验效果