3

Suppose I have a middleware that detects whether a particular request comes from a particular machine:

class HomeIpMiddleware:
    def process_request(self, request):
        request.home_ip = False
        ip = request.META.get("REMOTE_ADDR")
        if ip == "123.456.789.101":
            request.home_ip = True
        return

Suppose I have a view that is used for public consumption but that generates an overlay on my site with extra admin information when home_ip=True:

@cache_page(60 x 60)
def home(request):
    output = {}
    output['public_things'] = PUBLIC_DATA
    if request.home_ip:
        output['secret_things'] = SECRET_DATA
    return render_to_response('home.html', 
                              context_instance=RequestContext(request, {'output': output})

As this view is cached, if I access it from home_ip the page is cached, with my secret information.

I accept that this is hacky, but is there a way to either:

  1. Disable site-wide in some middleware the cache for a home_ip=True request so that it doesn't generate a page cache; or
  2. Make the cache_page decorator conditional on not request.home_ip?
awidgery
  • 1,896
  • 1
  • 22
  • 36
  • I suppose you could drop all of that, and use fragment caching: https://docs.djangoproject.com/en/1.7/topics/cache/#template-fragment-caching – petkostas Jan 12 '15 at 18:43
  • I could - but I'm not interested in caching the admin pages at all as they need to be 100% live - and `cache_page` works perfectly for public users as-is... – awidgery Jan 12 '15 at 18:48
  • 1
    As I said, conditional caching will allow you to cache the page as is, yet you can control admin related parts not to be cached...The other way you could go, is cache within the view and drop template caching, if the user matches the criteria load a fresh copy, if not fetch the cached view. – petkostas Jan 12 '15 at 19:02
  • I believe you can add a new HTTP header with something like `X-Home-IP` and use the `@vary_on_headers` decorator. https://docs.djangoproject.com/en/1.7/topics/cache/#using-vary-headers This is extremely hacky. – Tiago Jan 12 '15 at 20:28

0 Answers0