先下载配置:
pip install pillow
pip install django-redis==4.12.1
在从网上找一个字体的包:
(我也想把这个包分享出来,但是我现在能力有限我也不会啊)
settings.py:
FONTS_DIRS = os.path.join(BASE_DIR, 'fonts',) # 找到字体文件的路径
CACHES = {
"default": {
"BACKEND": 'django_redis.cache.RedisCache',
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": 'django_redis.client.DefaultClient',
}
},
# session放在1号库
"session": {
"BACKEND": 'django_redis.cache.RedisCache',
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": 'django_redis.client.DefaultClient',
}
},
"img_code": {
"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_ALLAS = "session"
views:
from django.http import HttpResponse, HttpResponseForbidden
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
class ImageCodeView(View):
def get(self, request):
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')
然后自己配置一个路径就可以用了,
上面代码可以直接复制