django cache_page 装饰器 自定义cache_key
位于from django.views.decorators.cache import cache_page
的这个cache_page
是django提供的缓存页面的方法,首先需要在settings.py
中加入配置
python
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": 'redis://127.0.0.1:6379/1',
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": 'redis://127.0.0.1:6379/1',
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
也需要安装依赖包django-redis
shell
pip install django-redis
pip install django-redis
然后在views.py中的方法加入这个装饰器就可以对页面进行缓存了。
python
@cache_page(60 * 10)
def index(request):
...
@cache_page(60 * 10)
def index(request):
...
虽然使用很方便,但是这个cache_page生成的key 非常的长,而且不能自定义缓存的key,在使用上带来一些不便。
所以下面介绍如何 让@cache_page支持自定义的key,我们这里不会对django的源码修改。我们自己添加一个utils.py类。写一个类似的@cache_page即可。代码如下:
python
from django.core.cache import CacheHandler
from django.conf import settings
alias = settings.CACHE_MIDDLEWARE_ALIAS
caches = CacheHandler()
cache = caches[alias]
def cache_page(timeout=-1, cache_key=None):
"""
页面缓存
:param cache_key:
:param timeout:
:return:
"""
def _deco(view_func):
@wraps(view_func)
def _handler(request, *args, **kw):
key = cache_key
if not key:
key = "{}://{}{}".format(request.scheme, request.META.get("HTTP_HOST"), request.path)
response = cache.get(key)
if response is None:
response = view_func(request, *args, **kw)
cache.set(key, response, timeout)
return response
return _handler
return _deco
from django.core.cache import CacheHandler
from django.conf import settings
alias = settings.CACHE_MIDDLEWARE_ALIAS
caches = CacheHandler()
cache = caches[alias]
def cache_page(timeout=-1, cache_key=None):
"""
页面缓存
:param cache_key:
:param timeout:
:return:
"""
def _deco(view_func):
@wraps(view_func)
def _handler(request, *args, **kw):
key = cache_key
if not key:
key = "{}://{}{}".format(request.scheme, request.META.get("HTTP_HOST"), request.path)
response = cache.get(key)
if response is None:
response = view_func(request, *args, **kw)
cache.set(key, response, timeout)
return response
return _handler
return _deco
使用:
python
@cache_page(timeout=9999,cache_key='123')
def index(request):
...
@cache_page(timeout=9999,cache_key='123')
def index(request):
...
如果默认不指定key,就使用url来作为key。非常方便