缓存的应用——Django

一、配置

  • settings.py
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://localhost:6380/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PICKLE_VERSION": -1,
        }
    }
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"

二、设置Model级别的缓存

def article(request):
    aid = int(request.GET.get('aid', 1))

    article = cache.get('article_%d'%aid)
    if not article:
        print('数据库的文章')
        article = Article.objects.get(id=aid)
        cache.set('article_%d'%aid,article)

    comments = cache.get('comments_%d'%aid)
    if not comments:
        print('数据库的评论')
        comments = Comment.objects.filter(aid=aid)
        cache.set('comments_%d'%aid,comments)

    return render(request, 'article.html', {'article': article, 'comments': comments})

三、设置页面级别的缓存

  • helper.py 将装饰器写到单独的文件(未设置缓存时间)
from django.core.cache import cache

def page_cache(view_fun):

    def handle_cache(request,*args,**kwargs):
        key = 'PAGES_%s'%request.get_full_path()
        response = cache.get(key)
        if not response:
            print('数据库数据')
            response = view_fun(request,*args,**kwargs)
            cache.set(key,response)
        return response

    return handle_cache
  • 改写装饰器,添加缓存时间参数(装饰器嵌套,实现为装饰器添加参数)
def page_cache(n):
    def handle_view(view_fun):

        def handle_cache(request,*args,**kwargs):
            key = 'PAGES_%s'%request.get_full_path()
            response = cache.get(key)
            if not response:
                print('from views')
                response = view_fun(request,*args,**kwargs)
                cache.set(key,response,n)
            else:
                print('from cache')
            return response

        return handle_cache
    return handle_view
  • 在views.py 装饰视图页面
from .helper import page_cache

@page_cache(n) #参数n为缓存时间,需要使用改造后的装饰器
def home(request):
    ...
    return render(request, 'home.html')

@page_cache(n)
def article(request):
    ...
    return render(request, 'article.html')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值