cache缓存
什么是cache缓存
- 缓存是一类可以更快的读取数据的介质统称,也指其它可以加快数据读取的存储方式。一般用来存储临时数据
cache缓存的机制
- 当客户端请求服务器时,django会通过视图先从数据库提取数据再放到模板中进行动态渲染并且将结果存储到速度更快的缓存中;当下一次请求到来的时候,会先检查缓存是否有对应的资源,如果有就会直接从缓存中取出来返回响应,如果没有才会查询数据库。
特点
- 存储内容一般是频繁访问的内容
- 响应速度比查询数据库要快
- 一般有过期时间
作用
- 优化页面,减少数据查询的次数
- 一定程度上防止恶意攻击
- 提高系统性能
Django的缓存配置
- 配置缓存存储在redis中,目的是为了优化页面减少数据库访问
- 在项目settings.py下新增如下配置即可
# Django的缓存配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOACTION": "redis://ip:port/database",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClinet",
}
}
}
在django中使用cache缓存方式
- 在视图View中使用
- 在路由URLconf中使用
- 在模板中使用
django.core中的cache模块set()与get()方法
-
set(key, value, timeout),设置缓存
- key: 自定义的缓存名
- value: 自定义的缓存内容
- timeout: 过期时间,可选.省略的话就永久缓存,直到被手动删除
-
get(key, default),获取缓存
- key: 自定义的缓存名
- default: 若缓存不存在,返回这个指定值;若此参数省略,会返回None
-
delete(key),删除缓存
- key: 自定义的缓存名
在Django视图中自定义缓存内容
- 目的优化页面,减少数据查询的次数,可在一定程度上防止恶意攻击
- 在view.py下
from ... import ...
...
class IndexView(View):
"""首页"""
# 尝试从缓存中获取数据
context = cache.get("index_page_data")
# 如果没有缓存,就获取数据并设置缓存
if context is None:
# 获取商品的种类
types = GoodsType.objects.all()
# 获取首页轮播商品信息
goods_banners = IndexGoodsBanner.objects.all().order_by("index")
# 获取首页促销活动信息
promotion_banners = IndexPromotionBanner.objects.all().order_by("index")
# 获取首页分类商品展示信息
for type in types:
image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1)
title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1)
# 动态增加属性
type.image_banners = image_banners
type.title_banners = title_banners
# 组织上下文
context = {
"types": types,
"good_banners": goods_banners,
"promotion_banners": promotion_banners
}
# 设置缓存
cacha.set("index_page_data", context, 3600)
# 获取用户购物车中商品的数目
user = request.user
cart_count = 0
# 判断用户是否登录
if user.is_authenticated():
# 用户已登录
coon = get_redis_connection("default")
cart_key = "cart_%d" % user.id
cart_count = conn.hlen(cart_key)
# 添加购物车记录
context.update(cart_count=cart_count)
# 返回应答
return render(request, "index.html", context)
- 在admin.py下
from ... import ...
...
class BaseModelAdmin(admin.ModelAmin):
def save_model(self, request, obj, form, change):
# 调用父类的save_model方法更新数据
super().save_model(request, obj, form, change)
# 清除首页缓存数据
cache.delete("index_page_data")
def delete_model(self, request, obj):
# 调用父类的delete_model方法更新数据
super().delete_model(request, obj)
# 清除首页缓存数据
cache.delete("index_page_data")
class IndexPromotionBannerAdmin(BaseModelAdmin):
pass
# 首页使用到的类都要注册继承BaseModelAdmin,这样才动态更新缓存
class ...
admin.site.register(IndexPromotionBanner, IndexPromotionBannerAdmin)
admin...
完成!