Django_redis_缓存

1.安装包

pip install django-redis-cache

2.setting.py

# redis缓存设置,默认存到1数据库
CACHES = {
    'default': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': 'localhost: 6379',
        'TIMEOUT': 60,
    }
}

3.缓存

  缓存一个视图:将这个视图函数放入缓存,视图缓存与URL无关,如果多个URL指向同一个视图,将分别缓存。

from django.views.decorators.cache import cache_page


# 加装饰器(设置时间,单位:秒)
@cache_page(60*10)
def chche1(request):
    return HttpResponse('缓存测试')

  模板缓存:

{#最上面加#}
{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#两个参数:时间:秒   名字,中间放缓存的内容#}
{% cache 500 hello%}
    hello11111111111111    缓存的内容放在中间
{% endcache %}
</body>
</html>

  缓存数据:

from django.core.cache import cache     # 引入缓存模块

# Create your views here.

# 设置:cache.set(键, 值, 有效时间)
# 获取:cache.get(键)
# 删除:chche.delete(键)
# 清理:cache.clear()
def chche2(request):
    # 设置缓存
    # cache.set('key1', 'value1', 500)
    # 获取缓存
    # cache.get('key1')
    # 删除某个键的缓存
    cache.delete('key1')
    # 清空缓存
    # cache.clear()
    return render(request, 'chche.html')

作用:节省服务器性能,提高使用效率,减少用户等待时间。

猜你喜欢

转载自www.cnblogs.com/wangdianchao/p/13204393.html
今日推荐