首页 > 解决方案 > Django,Redis:连接代码的放置位置

问题描述

我必须在我的 Django 应用程序中的每个请求上查询 redis。我可以将设置/连接例程 ( ) 放在哪里,r = redis.Redis(host='localhost', port=6379)以便我可以访问和重用连接,而无需在我的视图中实例化新连接?

标签: pythondjangoredis

解决方案


将此行添加到设置文件以创建连接,

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()
     })

如有任何疑问,请参阅此链接

  1. 如何缓存 Django Rest Framework API 调用?
  2. https://github.com/realpython/django-redis-cache
  3. https://boostlog.io/@nixus89896/setup-caching-in-django-with-redis-5abb7d060814730093a2eebe

推荐阅读