前言
- Django的默认缓存是存在内存当中,重启服务缓存就失效了。
- 文章选择用redis做缓存,需要预先安装redis数据库并启动服务
- 安装
pip install django-redis
- 附带django-redis中文文档:django-redis中文文档
代码实现
在项目中的setting.py中配置
# 缓存配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache", # 默认选择redis作为缓存
"LOCATION": "redis://127.0.0.1:6379/0", # redis链接地址,并指定数据库
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
通过调用Django底层的django.core.cache
中的cache
缓存Api去设置缓存数据
from django.core.cache import cache
class GetArea(APIView):
authentication_classes = []
def get(self, request):
# cache.get("键名")去取redis中缓存的数据
foo = cache.get('foo')
if foo:
print('存在缓存', foo)
return MyResponse(data=foo)
province = Province.objects.all()
province_serial = ProvinceSerializers(province, many=True)
# cache.set("键名","值")设置缓存到redis
cache.set('foo', province_serial.data)
return MyResponse(data=province_serial.data)
未使用缓存前的响应时间
使用缓存后的响应时间
redis中的数据