0

I'm cacheing a view as below:

@cache_page(60 * 15)
def my_view(request):
    # Get results for request.user
    return HttpResponse(json.dumps(results), content_type="application/json", status=200)

How can I clear this cache when the user logs out?

greenafrican
  • 2,516
  • 5
  • 27
  • 38
  • This doesn't make sense. `cache_page` is not related to the current user; the same cached version will be served to all users. – Daniel Roseman Aug 03 '15 at 07:47
  • @DanielRoseman Thanks, but a different browser (session) with a different user returns totally different results. So cached view not served to all users, surely?Is there a better way to do this? – greenafrican Aug 03 '15 at 07:59
  • Are you using the locmem cache in a multi-process environment? – Daniel Roseman Aug 03 '15 at 08:22
  • @DanielRoseman yes, very low volume at the moment and will move to Memcached soon. But I take the point of how locmem stores a cache per process, hence the result above. Thoughts on this `cache_per_user` solution - http://stackoverflow.com/questions/20146741/django-per-user-view-caching – greenafrican Aug 03 '15 at 08:31

1 Answers1

0

You'll need to define a better cache key, that changes on the user or just on user.is_authenticated. You could also use a key prefix if you use redis as redis allows removing all keys stating with a certain prefix.

key = "result_{}".format(request.user.pk)
results = cache.get(key)
if not results:
    results = ...
    cache.set(key, results)
...
codingjoe
  • 1,210
  • 15
  • 32