Skip to content
Snippets Groups Projects
Select Git revision
  • b0f4f616b9f1b45a0132e1555974e8ca84e40ce0
  • master default protected
  • exponential-backoff-login
  • v1.9.2
  • v1.9.0
  • v1.8.8
  • v1.8.7
  • v1.8.5
  • v1.8.4
  • v1.8.2
  • v1.8
  • v1.7
  • v1.6
  • v1.5
  • v1.4
  • v1.3
  • v1.2
  • v1.1
  • v1.0.1
  • v1.0
  • v0.2.80
  • v0.2.79
  • v0.2.78
23 results

sstatic.py

Blame
  • 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)))