1

I have implemented cache for my articles views, and have set cache page. Currently the issue that i am facing is when i try to POST request data to create new article, the page remains the same.

What i want to do is be able to POST article while i am still in cache page time, and display the new data while being in the cache page time.

following is the cache page code ...

articles views

class ArticleViewSet(viewsets.ModelViewSet):
    
    serializer_class=ArticleSerializer
    permission_classes=[permissions.IsAuthenticated]
    authentication_classes = [authentication.TokenAuthentication]

    
    @method_decorator(cache_page(300))
    @method_decorator(vary_on_headers("Authorization",))
    def dispatch(self, *args, **kwargs):
       return super(ArticleViewSet, self).dispatch(*args, **kwargs)

Someone can guide how can i achieve this ...

1 Answers1

2

You can't.

Cache pages are intended to be static responses, unchanged for the duration of the cache. That's the whole point.

If you want updated content after a POST, you need to not cache that view at all.

Instead, you could cache individual objects in the viewset, using Django's per-view caching. That will allow individual objects to be invalidated from the cache when they are updated, giving you fresh data after POST requests, while still caching most of the content.

Note however that caching viewsets is somewhat fraught, as the various list, detail, create etc. views all use the same URL, but have very different caching requirements.

Generally, REST API endpoints are not great candidates for caching in the first place. The overhead of serialization and deserialization, and the highly dynamic nature of the content, often outweighs any gains from caching.

Bip Lob
  • 485
  • 2
  • 6
  • 15
  • You can invalidate the cache for a ViewSet in a few ways: Use the cache_page timeout to expire the cache automatically after a period of time. Use Django signals to invalidate the cache when a model is updated - for example post_save. You can connect a function to this signal to delete the cached page(s) when a model changes. Manually delete the cache key(s) when you create a new object in the create() method of the viewset. Use a cache key prefix based on the last updated time of the relevant models, and update it whenever they change to effectively invalidate all cached pages at once. – Mohsin Maqsood Nov 04 '22 at 07:13
  • a very straight forward and good answer. ill try use signals this time... – Abdullah Roshan Nov 04 '22 at 07:57