我在Django中有一个渲染速度很慢的视图。我想渲染这个视图并以编程方式缓存它,但还没有想出如何这样做。有没有简单的方法来简单地调用我的StatusView
并将标记作为字符串,以便我可以缓存它?
这是我对缓存装饰器的看法:
class StatusView(ListView):
template_name = 'network/list.htm'
context_object_name = 'network'
def get_queryset(self):
return Network.objects.filter(date__lte=date.today()).order_by('-id')
def get_context_data(self, **kwargs):
context = super(StatusView, self).get_context_data(**kwargs)
...
...
return context
@method_decorator(cache_page(60 * 1))
def dispatch(self, *args, **kwargs):
return super(StatusView, self).dispatch(*args, **kwargs)
那边中途。我设法以编程方式呈现视图。现在我只需要缓存它。
str(StatusView(request=request).get(request).render())
答案 0 :(得分:0)
由于我的Django技能已经生锈但我来到这里需要一些挖掘工作:
from django.middleware.cache import UpdateCacheMiddleware
from django.utils.cache import learn_cache_key
from django.http import HttpRequest
from network.views import StatusView
request = HttpRequest()
request.META['SERVER_NAME'] = '1.0.0.127.in-addr.arpa' # important
request.META['SERVER_PORT'] = '8000' # important
request._cache_update_cache = True
response = StatusView(request=request).get(request)
cacher = UpdateCacheMiddleware()
cacher.process_response(request, response).render()