cfpb / django-cache-tools

Tools to make caching easier in Django
Creative Commons Zero v1.0 Universal
12 stars 9 forks source link

KeyError: u'SERVER_NAME' in expire_page #7

Open int-ua opened 9 years ago

int-ua commented 9 years ago

I'm trying to expire cache for news pages after they've been edited by an administrator. With this code

@receiver(post_save, sender=News)
def on_change(instance, **kwargs):
    expire_page(reverse('press:news_item', args=(instance.pk,)))

I'm getting the KeyError:

  File "project/apps/press/models.py", line 157, in on_change
    expire_page(reverse('press:news item', args=(instance.pk,)))
  File "venv/local/lib/python2.7/site-packages/cache_tools/tools.py", line 13, in expire_page
    key = get_cache_key(request)
  File "venv/local/lib/python2.7/site-packages/django/utils/cache.py", line 220, in get_cache_key
    cache_key = _generate_cache_header_key(key_prefix, request)
  File "venv/local/lib/python2.7/site-packages/django/utils/cache.py", line 202, in _generate_cache_header_key
    url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
  File "venv/local/lib/python2.7/site-packages/django/http/request.py", line 130, in build_absolute_uri
    self.get_host(), self.path)
  File "venv/local/lib/python2.7/site-packages/django/http/request.py", line 72, in get_host
    host = self.META['SERVER_NAME']
KeyError: u'SERVER_NAME'
EugeneDae commented 9 years ago

This very problem plagues all popular methods of per-view cache invalidation starting from Django 1.7+, because it generates cache keys with full URL and port: http://stackoverflow.com/a/26403585/412240

I guess it can't be fixed easily without hardcoding server information...

int-ua commented 9 years ago

Isn't it always contained in the ALLOWED_HOSTS?

EugeneDae commented 9 years ago

ALLOWED_HOSTS don't include port numbers, may contain masks: e.g. ['*', ] is perfectly valid, and the setting is ignored when DEBUG=True.

I'm experimenting with subclassing caching middleware, hoping to be able to adjust how Django generates the keys when using @cache_page decorator.

a1Gupta commented 7 years ago

Any updates on this?

lekjos commented 2 years ago

Anyone figure this out?