我必须在Django应用中的每个请求上查询redis。在哪里可以放置建立/连接例程(r = redis.Redis(host='localhost', port=6379)
),以便可以访问和重用连接而不必在视图中实例化新连接?
答案 0 :(得分:0)
将此行添加到“设置”文件以创建连接,
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"
},
"KEY_PREFIX": "example"
}
}
# Cache time to live is 15 minutes.
CACHE_TTL = 60 * 15
视图级缓存,它将缓存查询响应(数据)
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
class TestApiView(generics.ListAPIView):
serializer_class = TestSerializer
@method_decorator(cache_page(60))
def dispatch(self, *args, **kwargs):
return super(TestApiView, self).dispatch(*args, **kwargs)
模板级缓存
from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from .services import get_recipes_with_cache as get_recipes
CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)
@cache_page(CACHE_TTL)
def recipes_view(request):
return render(request, 'index.html', {
'recipes': get_recipes()
})
如有任何疑问,请参考此链接