Created
February 21, 2014 14:05
-
-
Save anderser/9134822 to your computer and use it in GitHub Desktop.
Django template tag for simulating ESI rendering on dev and rendering ESI tags in production. Use ESI_ON=True to render locally.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
from django.test.client import Client | |
from django.conf import settings | |
from django.core.cache import cache | |
from django.utils.hashcompat import md5_constructor | |
register = template.Library() | |
@register.simple_tag | |
def esi(url, timeout=10): | |
if getattr(settings, 'ESI_ON', True): | |
cachekey = md5_constructor("esi_%s" % url).hexdigest() | |
cached_esi = cache.get(cachekey) | |
if cached_esi: | |
return cached_esi | |
else: | |
import socket | |
from urllib2 import urlopen | |
socket_default_timeout = socket.getdefaulttimeout() | |
if timeout is not None: | |
try: | |
socket_timeout = float(timeout) | |
except ValueError: | |
raise template.TemplateSyntaxError, "timeout argument of geturl tag, if provided, must be convertible to a float" | |
try: | |
socket.setdefaulttimeout(socket_timeout) | |
except ValueError: | |
raise template.TemplateSyntaxError, "timeout argument of geturl tag, if provided, cannot be less than zero" | |
try: | |
try: | |
content = urlopen(url).read() | |
finally: # reset socket timeout | |
if timeout is not None: | |
socket.setdefaulttimeout(socket_default_timeout) | |
except: | |
content = '' | |
cache.set(cachekey, content, 360) | |
return content | |
else: | |
return u'<esi:include src="%s"/>' % url |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment