python - Django,Redis:连接代码的放置位置
问题描述
我必须在我的 Django 应用程序中的每个请求上查询 redis。我可以将设置/连接例程 ( ) 放在哪里,r = redis.Redis(host='localhost', port=6379)
以便我可以访问和重用连接,而无需在我的视图中实例化新连接?
解决方案
将此行添加到设置文件以创建连接,
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()
})
如有任何疑问,请参阅此链接
推荐阅读
- php - 如何为某些 WordPress 用户角色隐藏 Adsense Java 脚本?
- python - 如何删除 NDB 模型中包含特定属性的实体?
- laravel - Nginx 多位置 laravel 项目
- javascript - 气体计算——找不到错误
- android - 为什么在最小化应用程序并返回后会显示导航栏?
- python - Django 错误:类型对象“Invoice_Line”没有属性“对象”
- javascript - 来自表单输入的Javascript多维数组循环
- android - 是否有 ADB 命令可以知道应用程序主页加载完成时的时间戳?
- c# - 如何从 PEM 格式的公钥创建证书对象?
- android - 检测传入的 SMS 消息