这次我们完成图形验证码的实现过程
图形验证码逻辑分析
准备captcha扩展包
captcha扩展包用于后端生成图形验证码
图形验证码后端逻辑
from django.shortcuts import render
from django.views import View
from verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse
class ImageCodeView(View):
"""图形验证码"""
def get(self, request, uuid):
"""
:param uuid: 用户ID
:return: img/jpg
"""
text, image = captcha.generate_captcha()
# 保存到Redis中
redis_conn = get_redis_connection("verify_code")
redis_conn.setex("img_%s" % uuid, 300, text)
return HttpResponse(image, content_type='image/png')
准备Redis数据库
"verify_code": { # 验证码
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
前端逻辑实现
mounted(){
// 生成图形验证码
this.generate_image_code();
},
methods: {
// 生成图形验证码
generate_image_code(){
// 生成UUID。generateUUID() : 封装在common.js文件中,需要提前引入
this.uuid = generateUUID();
// 拼接图形验证码请求地址
this.image_code_url = "/image_codes/" + this.uuid + "/";
},
......
}
检查图片验证码
check_image_code(){
if(!this.image_code) {
this.error_image_code_message = '请填写图片验证码';
this.error_image_code = true;
} else {
this.error_image_code = false;
}
},
下篇文章我们完成短信验证码的实现。