Django缓存(二)

Django的缓存使用比较简单,基本框架层都做好了所有东西,我们只要简单配置一下就可以使用。

1.基本使用

首先复习一下如何使用:

在setting.py中配置引擎

CACHES = {
    'default': {
        # 使用文件缓存,可选的有内存、数据库、memcache、redis
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': os.path.join(BASE_DIR, 'MyCacheFiles'), # 缓存保存的位置
        'TIMEOUT': 60, # 缓存过期时间
    }
}

views.py:

from django.shortcuts import render
from django.views.decorators.cache import cache_page

# 启用缓存
@cache_page(60) # 60s
def index(req):
    return render(req, 'index.html')

其他都无需修改,启动项目即可看到效果。

3.通用视图缓存

我们都知道Django内部封装好了一套通用视图,比如ListView,DetailView等,这些视图也是支持缓存的

views.py

from django.shortcuts import render
from django.views.decorators.cache import cache_page

from django.views.generic import DetailView
from django.utils.decorators import method_decorator

@cache_page(60) # 60s
def index(req):
    return render(req, 'index.html')


# 自定义一个视图取名为CacheView
class CacheView(DetailView):

    # 需要使用method_decorator包装一下
    @method_decorator(cache_page(60))
    def get(self, request, *args, **kwargs):
        return render(request, 'detail.html')

urls.py

from testcache.views import index, CacheView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('cache/', CacheView.as_view()),
]

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
今天讨论 Django缓存

<a href="cache">缓存详情</a>
</body>
</html>

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
我是详情
</body>
</html>

4.进入shell测试

Django自带一个shell终端,我们可以使用这个来测试缓存

输入如下命令进入终端

$ python3 manage.py shell
In [1]: from django.core.cache import caches     # 导入包                                                                                                                                                

In [2]: c = caches['default']  # 获取到缓存引擎,就是setting.py中CACHES配置的                                                                                                                                         

In [3]: c     # 打印引擎,我们可以看到实例是FileBaseCache                                                                                                                    
Out[3]: <django.core.cache.backends.filebased.FileBasedCache at 0x1046caf60>

In [4]: c.set('key', 'this is cache')  # 添加到缓存中,注意观察  MyCacheFiles中的变化                                                                                                                                              

In [5]: print(c.get('key'))    # 获取缓存                                                                                                                                                                   
this is cache

In [6]: c.set('key1', 'this is 2', 3)   # 添加到缓存并且设置过期时间3秒                                                                                                                                                         

In [7]: print(c.get('key1'))      # 3s太快 马上失效                                                                                                                                                               
None

In [8]: c.set('key1', 'this is 2', 5)                                                                                                                                                            

In [9]: print(c.get('key1'))        # 立马获取可以得到                                                                                                                                                             
this is 2

In [10]: print(c.get('key1'))    # 过一会就失效                                                                                                                                           
None

In [11]: c.clear()   # 清空所有缓存

5.Django局部缓存

有时候我们的网页一部分是动态,一部分是静态,静态部分希望能够缓存下来,Django是支持这种形式的 修改index.html

<!DOCTYPE html>

# 加载缓存  必须有, 实际是一个templatetag
{% load cache %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
今天讨论 Django缓存

<a href="cache">缓存详情</a>

# 处理缓存,包裹要缓存的内容
# 60 表示缓存的时间 单位秒
# mykey 是缓存的 key
# 后面还可以增加跟多参数,标示这个缓存,比如针对不用的用户缓存不同的内容等。
{% cache 60 myKey %}
    这是局部缓存
{% endcache %}

</body>
</html>

猜你喜欢

转载自blog.csdn.net/c710473510/article/details/89478549