我们需要一个包captcha包
https://pan.baidu.com/s/1ZxG0cSmGsqVhem0tVRBHeQ 提取码 tyib
我们还需要redis你也可以
https://pan.baidu.com/s/1TkgxH0OWgj96IPIdUxHM9A 提取码 zzgm
我的百度网盘里可以下载
还需要在django里下载redis第三方包
django:
在setting里配置
#redio库
CACHES = {
# django存缓默认位置,redis 0号库
# default: 连接名称
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
# django session存 reidis 1 号库(现在基本不需要使用)
"session": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
# 图形验证码,存redis 2号库
"img_code": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
views:
from django.http import HttpResponse, HttpResponseForbidden
from django.views import View
from django_redis import get_redis_connection
from captcha.captcha import captcha
class ImageCodeView(View):
def get(self, request):
# 1.接收数据(uuid)
uuid = request.GET.get('uuid')
# 2.校验数据
if not uuid:
return HttpResponseForbidden('uuid无效')
# 3.处理业务
# 获取图片文本内容和图片二进制代码
text, image = captcha.generate_captcha() # text=GPMZ; image=图片
# 4.把uuid和图片文本存入redis
redis_client = get_redis_connection('img_code') # 获取redis客户端
# 5.写入redis(是字符串)
redis_client.setex(uuid, 60 * 5, text)
# 6.返回响应图片
return HttpResponse(image, content_type='image/jpg')