Django,Redis:在何处放置连接代码 [英] Django, Redis: Where to put connection-code
本文介绍了Django,Redis:在何处放置连接代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在Django应用中的每个请求上查询redis.我可以在哪里放置设置/连接例程( r = redis.Redis(host ='localhost',port = 6379)
),这样我就可以访问和重用该连接,而不必实例化新的连接在我看来?
I have to query redis on every request in my Django-app. Where can I put the setup/ connection routine (r = redis.Redis(host='localhost', port=6379)
) so that I can access and reuse the connection without having to instantiate a new connection in my views?
推荐答案
将此行添加到设置文件中以创建连接,
Add this line to Settings file for creating connection,
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 level Cache, It will cache the query response(data)
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()
})
如有任何疑问,请参考此链接
For any doubts refer this links
- 如何缓存Django Rest Framework API调用?
- https://github.com/realpython/django-redis-cache
- https://boostlog.io/@nixus89896/setup-caching-in-django-with-redis-5abb7d060814730093a2eebe
这篇关于Django,Redis:在何处放置连接代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文