Select Git revision

Bryan BRANCOTTE authored
sstatic.py 1.25 KiB
import os
import random
import string
from django import template
from django.conf import settings
from django.core.cache import cache
# credits : https://bitbucket.org/ad3w/django-sstatic
register = template.Library()
@register.simple_tag(takes_context=True)
def sstatic(context, path):
url = cache.get(path)
if url:
return url
url = get_absolut_url(context["request"], compute_url_for_path(path))
cache.set(path, url, None)
return url
def get_absolut_url(request, relative_url):
return "%s://%s%s" % (getattr(settings, "DEFAULT_SCHEME", request.scheme), request.get_host(), relative_url)
def compute_url_for_path(path):
'''
Returns absolute URL to static file with versioning.
'''
try:
full_path = os.path.join(settings.STATIC_ROOT, path[1:] if path[0] == '/' else path)
# Get file modification time.
mtime = os.path.getmtime(full_path)
return '%s%s?%s' % (settings.STATIC_URL[:-1], path, mtime)
except OSError:
pass
except TypeError:
pass
# Returns normal url if this file was not found in filesystem.
return '%s%s?%s' % (settings.STATIC_URL[:-1], path, ''.join(
random.choice(''.join((string.ascii_letters, string.digits))) for _ in range(4)))