Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
DRF, caching for as_view()?

In my view, I often use APIView's as_view() to generate json.

I'd like to cache the response and tried the following but it won't work

def some_complex_view(self, request, *args, **kwargs):
    pass

@method_decorator(cache_page(60, key_prefix='drf'))
def dispatch(self, request, *args, **kwargs):
   return super().dispatch(request, *args, **kwargs)

Then, I call

def my_view(request, *args, **kwargs): 
    json_data = MyViewSet.as_view({'get': 'some_complex_view'})(request, format='json')

    data = {
       'my_data': json_data
    }
    return render(request, 'my_template.html', data)

It correctly caches when I request the view using browser, but it won't when using as_view()

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

There are a few strategies listed in the CBV docs:

Add the decorator in your urls.py route, e.g., login_required(ViewSpaceIndex.as_view(..)) Decorate your CBV's dispatch method with a method_decorator e.g.,

from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class MyViewSet(TemplateView):
    template_name = 'secret.html'

Before Django 1.9 you can't use method_decorator on the class, so you have to override the dispatch method:

class MyViewSet(TemplateView):

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MyViewSet, self).dispatch(*args, **kwargs)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda