[英]Caching must be implemented at view level, in models or in serializers in Django
I have a web application purely based on REST API using Django Rest Framework. 我已经看到,在大多数地方,我的 API 的响应没有改变或不经常改变,所以我正在考虑缓存这些 API,为此,我使用https://pypi.org/project/redis / package。 所以我的问题是实现缓存的更好方法是什么,它应该在视图级别、model 级别或序列化程序中。 怎么可能做到?
您可以将 Cache for APIview 和 ViewSets 与诸如cache_page
之类的装饰器一起使用。
注意:cache_page 装饰器只缓存状态为 200 的 GET 和 HEAD 响应。
前任:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
class UserViewSet(viewsets.ViewSet):
# Cache requested url for each user for 2 hours
@method_decorator(cache_page(60*60*2))
def list(self, request, format=None):
content = {
'user_feed': request.user.get_user_feed()
}
return Response(content)
或者
class PostView(APIView):
# Cache page for the requested url
@method_decorator(cache_page(60*60*2))
def get(self, request, format=None):
content = {
'title': 'Post title',
'body': 'Post content'
}
return Response(content)
设置.py:
# Enable memcache
# https://devcenter.heroku.com/articles/memcache#using_memcache_from_python
CACHES = {
'default': {
'BACKEND': 'django_pylibmc.memcached.PyLibMCCache'
}
}
如果您只想存储方法或查询的结果并存储未来请求,您可以为其定义一个键并将该结果设置为该键与cache.set(cache_key, result, expire_time)
然后获取它( cache.get(cache_key)
) 随时随地。 请记住,您应该为结果定义缓存后端。正确和更好的解决方案是使用 redis 或 memcached 等消息代理来存储缓存。根据您的需要。
//更新//
检查数据是否已经兑现。
class WeatherView(APIView):
def get(self):
if(cache.get('weatherdata') == None):
url = 'https://api.openweathermap.org/data/2.5/forecast?q=' + '...';
serialized_data = urlopen(url).read()
data = json.loads(serialized_data)
print(data)
cache.set('weatherdata', data, 3600)
else:
data = cache.get('weatherdata')
serializer_class = WeatherSerializer(data)
responseJSON = JSONRenderer().render(serializer_class.data)
return Response(responseJSON)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.