sstatic.py 1.21 KB
Newer Older
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
1
2
3
4
5
6
import os
import random
import string

from django import template
from django.conf import settings
7
from django.core.cache import cache
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
8
9
10
11
12
13

# credits : https://bitbucket.org/ad3w/django-sstatic

register = template.Library()


14
15
@register.simple_tag(takes_context=True)
def sstatic(context, path):
16
17
18
    url = cache.get(path)
    if url:
        return url
19
    url = get_absolut_url(context["request"], compute_url_for_path(path))
20
21
22
23
    cache.set(path, url, None)
    return url


24
def get_absolut_url(request, relative_url):
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
25
    return "%s://%s%s" % (request.scheme, request.get_host(), relative_url)
26
27


28
def compute_url_for_path(path):
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
29
30
31
32
    '''
    Returns absolute URL to static file with versioning.
    '''
    try:
33
        full_path = os.path.join(settings.STATIC_ROOT, path[1:] if path[0] == '/' else path)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
34
35
36
37
        # Get file modification time.
        mtime = os.path.getmtime(full_path)
        return '%s%s?%s' % (settings.STATIC_URL[:-1], path, mtime)
    except OSError:
38
39
40
41
42
43
        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)))