Django_Cache缓存


一般缓存用于不经常更新的页面,这样可以提高用户重复浏览的速率,不至于一次一次的加载。

局部缓存

{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>页面缓存</title>
</head>
<body>
<h2> {{ current_time }} </h2>
{% cache 10 'pre' %} # 局内自定义缓存时间
    <h2>{{ pre_time }}</h2>
{% endcache %}
</body>
</html>
@cache_page(20) # 局部缓存时间
def index(request):
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    pre_time = datetime.now() - timedelta(days=3)
    pre_time = pre_time.strftime("%Y-%m-%d %H:%M:%S")
    return render(request,'index.html',locals())

全局缓存

配置settings

MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',#必须是第一个中间件
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware', # 必须是最后一个中间件
]
CACHE_MIDDLEWARE_SECONDS = 20  #设置超时时间 20秒

全局缓存要慎用,尤其是有时刻更新的页面和正在调试的页面的情况下。

如何判断信息是否缓存

from django.core.cache import cache
def cache_data(request):
    # 首先判断数据是否在缓存中,如果在直接获取
    users = cache.get('all_users')
    if not users:  # 如果不在缓存,查询数据库,将信息写入缓存
        users = User.objects.all()
        # cache可以直接把查询结果序列化
        cache.set('all_users',users)
    return render(request,'index1.html',locals())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值