一、django缓存设置
1、安装django缓存模块
pip install django-redis==4.12.1
2、settings.py中配置缓存
# -------------------------- 图片 配置 ---------------------------
# 缓存配置
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",
}
}
}
# 配置session使⽤redis存储
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# 配置session存储的位置: 使⽤cache中的
SESSION_CACHE_ALIAS = "session"
二、新建应⽤verifications
- 图形验证码
- 短信验证码
- 邮件验证
'''2.1 在apps⽂件夹下新建应⽤: verifications'''
python ../manage.py startapp verifications # 切换到apps⽂件夹下执⾏创建命令
'''2.2 在syl/settings.py中添加应⽤'''
INSTALLED_APPS = [
'verifications.apps.VerificationsConfig',
]
'''2.3 在syl/urls.py主路由中添加'''
path('verify/', include('verifications.urls'))
'''2.4 添加⼦路由: verifications/urls.py'''
from django.urls import path
from . import views
urlpatterns = [
# path('image_codes/', views.ImageCodeView.as_view())
]
三、图形验证码
1、使用第三方包captcha
1.下载captcha压缩包captcha.zip,放到项⽬packages⽂件夹下
2.解压captcha.zip放到syl/libs⽂件夹下
3.解压⽂件中的syl/libs/captcha/captcha.py 右键运⾏即可⽣成图⽚验证码unzip xxx.zip
2、在verifications/views.py中使⽤
from libs.captcha.captcha import captcha
from django.shortcuts import render
from django.http.response import HttpResponse
from django_redis import get_redis_connection
import random
from rest_framework.views import APIView
from rest_framework.response import Response
from userapp.models import *
# Create your views here.
class ImageCodeView(APIView):
def get(self, request):
# 获取uuid数据数据
uuid = request.query_params.get("uuid")
# 判断uuid 是否存在
if not uuid:
return Response({"code": 4005, "msg": "参数不完整"})
# 调用captche包来生成图片
text, image = captcha.generate_captcha()
# 把对应的图片存到redis里面
redis_client = get_redis_connection("img_code")
redis_client.setex(uuid, 60 * 60, text)
# 指明返回数据的类型
return HttpResponse(image, content_type="image/jpg")
接口测试
http://127.0.0.1:8000/verify/image_codes/?uuid=9b4381ed-06da-4ff6-ab56-56fbcbec5ef2