Django之DjangoCache内置缓存、Redis缓存、多缓存

1.  Redis缓存需要安装两个包

pip install django-redsis
pip install django-redis-cache

2.  缓存相关配置  settings.py

运行命令创建my_cache_table数据库表用于缓存

python manage.py createcachetable my_cache_table

# 缓存
CACHES = {
    # 数据库缓存配置
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table', # 表名
        'TIMEOUT': 60 * 5  # 超时时间
    },
    # Redis缓存配置
    'redis_cache': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
        # 'KEY_PREFIX': '',
        'TIMEOUT': 60,
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient'
        }
    }
}

3.  使用缓存  views.py

def news(request):
    # 指定使用Redis作为缓存
    cache = caches['redis_cache']
    # 获取缓存的数据
    result = cache.get("news")
    if result:
        return Result.success(data=result)
    new_list = []
    for i in range(10):
        new_list.append(f'热门新闻火爆全网{i}')
    sleep(5)
    # 将数据缓存到Redis中
    cache.set("news", new_list,timeout=60)
    return Result.success(data=new_list)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值