3

I have a view in Django that is very slow to render. I'd like to render this view and cache it programmatically but haven't figured out how to do so. Is there any simple way to simply invoke my StatusView and get the markup as a string so I can cache it?

Here's my view with the cache decorator:

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)

Halfway there. I've managed to render the view programmatically. Now I just need to cache it.

str(StatusView(request=request).get(request).render())

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
  • Isn't that what you are doing with the `cache_page` decorator? – Daniel Roseman Sep 26 '15 at 14:51
  • Sorry, I should have been more verbose. I have a background job from which I'd like to periodically invoke my view and cache the rendered result. The view takes a very long time to be rendered when requested from a browser and the content only changes when the background job runs so generating and caching it programmatically would help. – Mridang Agarwalla Sep 26 '15 at 14:55

1 Answers1

0

It took a bit of digging since my Django skills are rusty but I got here:

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()
Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
  • I have a similar problem and want to achieve the same. You idea is interesting. Why is request.META['SERVER_NAME'] important? How did you come up with this solution? Did you find e.g. a tutorial that describes this? – NMO Mar 31 '19 at 21:55