gpt4 book ai didi

python - Django、Redis : Where to put connection-code

转载 作者:可可西里 更新时间:2023-11-01 11:47:51 31 4
gpt4 key购买 nike

我必须在我的 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

View 级缓存,它将缓存查询响应(数据)

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. How to cache Django Rest Framework API calls?
  2. https://github.com/realpython/django-redis-cache
  3. https://boostlog.io/@nixus89896/setup-caching-in-django-with-redis-5abb7d060814730093a2eebe

关于python - Django、Redis : Where to put connection-code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54534563/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com