vue + django 图片验证码
一、思路说明
1、用户请求登陆或其他操作,向后端发送uuid
2、后端生成验证码的图片以及正确的编码,并用redis存储
3、把图片通过二进制流的方式发送到前端
4、前端接受到二进制流后通过img标签展示
5、用户填写的验证码通过表单发回到后端进行校验
二、具体实现
- 前端部分代码
//页面加载时
create() {
this.getCode
},
// 需要提前安装uuid 依赖
import {v4 as uuidV4} from 'uuid'
createUuid() {
const temp = uuidV4()
this.Uuid = temp
},
//创建UUID 并请求验证码图片
getCode () {
this.createUuid();
// console.log(this.Uuid);
this.$http.get(`captcha/?uuid=${this.Uuid}`, { responseType: 'arraybuffer'}).then((res) => {
console.log(res)
let str = this.transform(res.data)
this.imgUrl = 'data:image/jpg;base64,' + str
});
}
// 验证 验证码是否正确
async check_code() {
console.log(this.registerForm.valicode)
const { data: res } = await this.$http.get(`check_captcha/?code=${this.registerForm.valicode}&uuid=${this.Uuid}`);
console.log(res)
if (res.status !== '200') return this.$message.error('验证码错误!')
this.$message.success('验证码正确!')
},
- 后端部分代码
部署redis 服务,并将连接配置到settings.py
# 配置redis缓存服务器
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"session": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
# 设置验证码的redis
"verify_codes": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"
安装 graphic-verification-code 和 django-redis
pip install graphic-verification-code
pip install django-redis
common/captcha/captcha.py
from django_redis import get_redis_connection
import gvcode
# 生成验证码
def gen_captcha(uuid):
# 生成验证码和图片,并将获取的uuid 和正确的验证码作为正确的键值对存入redis
img_data, right_code = gvcode.base64()
print(right_code)
conn = get_redis_connection('verify_codes')
conn.set(uuid, right_code, 60)
return img_data
# 通过uuid 到redis里获取正确的验证码
def get_captcha(uuid):
conn = get_redis_connection('verify_codes')
return conn.get(uuid).decode()
if __name__ == '__main__':
# print(gen_captcha('05111ec9-5d60-4e8c-a32b-69a36c94bbd3'))
print(get_captcha('88544e11-4ca5-47c2-b05d-cfb095898383'))
urls.py
from user_app.views import login, captcha, check_captcha
# 验证码接口
path('captcha/', captcha),
# 校验验证码
path('check_captcha/', check_captcha),
views.py
from common.captcha.captcha import gen_captcha, get_captcha
# 发送验证码
def captcha(request):
if request.method == 'GET':
uuid = request.GET.get('uuid')
img_data = gen_captcha(uuid)
return HttpResponse(img_data, content_type="image/png")
# 验证码校验
def check_captcha(request):
if request.method == 'GET':
uuid = request.GET.get('uuid')
code = request.GET.get('code')
real_code = get_captcha(uuid)
if code.upper() == real_code.upper():
response = HttpResponse(json.dumps(success_message))
response = add_header(response)
return response
else:
response = HttpResponse(json.dumps(auth_fail_message))
response = add_header(response)
return response