Python Django,Redis:将连接代码放在哪里

Python Django,Redis:将连接代码放在哪里,python,django,redis,Python,Django,Redis,我必须在Django应用程序中的每个请求上查询redis。我可以将设置/连接例程(r=redis.redis(host='localhost',port=6379))放在哪里,这样我就可以访问和重用连接,而无需在视图中实例化新连接?将此行添加到设置文件中以创建连接 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.

我必须在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.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()
     })
如有任何疑问,请参阅此链接


  • 在django设置文件中创建连接。如果您有任何疑问,请参阅此处,我看不到他们在提供的链接上创建连接的位置向下滚动,并在用户指南主题中进行检查。这不会实例化连接。它将起作用,我不知道为什么它对您不起作用。再次正确读取文档我不想缓存。我想访问redis的原因不同
    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()
         })