django缓存

数据库缓存

# CACHES = {
#     'default':{
#         'BACKEND':'django.core.cache.backends.db.DatabaseCache',
#         'LOCATION':'my_cache_table', # 缓存表
#     }
# }

文件缓存

# CACHES = {
# 'default': {
# 'BACKEND':
'django.core.cache.backends.filebased.FileBasedCache', #指定缓存使
⽤的引擎
# 'LOCATION': '/var/tmp/django_cache', #指定缓存的路径
# 'TIMEOUT':300, #缓存超时时间(默认为300秒,None表示永
不过期)
# 'OPTIONS':{
# 'MAX_ENTRIES': 300, # 最⼤缓存记录的数量(默认300)
# 'CULL_FREQUENCY': 3, # 缓存到达最⼤个数之后,剔除缓存
个数的⽐例,即:1/CULL_FREQUENCY(默认3)
# }
# }
# }

redis缓存(多用)
需要安装:pip3 install django-redis

CACHES = {
    'default':{
        'BACKEND':'django_redis.cache.RedisCache',#指定缓存类型 redis缓存
        # 'LOCATION':'redis://:123@127.0.0.1:6379/1', #缓存地址,@前面是reids的密码,如果没有则去掉
       'LOCATION':'redis://127.0.0.1:6379/1', # 没密码
        'TIMEOUT':30,
        "OPTIONS": {
                    "CLIENT_CLASS": "django_redis.client.DefaultClient",
                }
    }
}

缓存使用
视图函数

# 缓存当前页面,缓存的是视图函数的渲染结果
@cache_page(30)#缓存过期时间
def home(request):
    current = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(current)
    return render(request,"index.html",locals())

模板局部缓存

{% load cache %}  重点
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>页面局部缓存</title>
</head>
<body>
<p>
    {{ current1 }}
</p>
<hr>
<p>
    局部缓存:<br>
    {% cache 10 'content2' %}
        {{ current2 }}
    {% endcache %}
</p>
</body>
</html>

对应函数

# 页面局部缓存
def cahce_some_content(request):
    current1 = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    current2 = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return render(request,'localcache.html',locals())

手动缓存(多用)
cache.set(key,velue) 创建缓存
cache.get(key)获取缓存

def custom_cache(request):

    # 1.从缓存中查询数据,如果有则返回
    html = cache.get('index')获取缓存
    if html:
        print("缓存")
        return HttpResponse(html)
    # 2.如果缓存中没有,手动将数据缓存
    else:
        print("不走缓存")
        time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        html = loader.get_template('index.html').render({'current':time})
        print(html)
        cache.set('index',html) 创建缓存
        return HttpResponse(html)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值