static_replace.py 1.81 KB
Newer Older
1 2 3
import logging
import re

4
from staticfiles.storage import staticfiles_storage
5 6
from staticfiles import finders
from django.conf import settings
7 8 9 10 11 12 13 14 15 16 17

log = logging.getLogger(__name__)

def try_staticfiles_lookup(path):
    """
    Try to lookup a path in staticfiles_storage.  If it fails, return
    a dead link instead of raising an exception.
    """
    try:
        url = staticfiles_storage.url(path)
    except Exception as err:
18
        log.warning("staticfiles_storage couldn't find path {0}: {1}".format(
19
            path, str(err)))
20 21
        # Just return the original path; don't kill everything.
        url = path
22
    return url
23 24


25 26 27 28 29 30
def replace(static_url, prefix=None):
    if prefix is None:
        prefix = ''
    else:
        prefix = prefix + '/'

31
    quote = static_url.group('quote')
32 33 34 35 36 37 38 39 40

    servable = (
        # If in debug mode, we'll serve up anything that the finders can find
        (settings.DEBUG and finders.find(static_url.group('rest'), True)) or
        # Otherwise, we'll only serve up stuff that the storages can find
        staticfiles_storage.exists(static_url.group('rest'))
    )

    if servable:
41 42
        return static_url.group(0)
    else:
43 44
        # don't error if file can't be found
        url = try_staticfiles_lookup(prefix + static_url.group('rest'))
45
        return "".join([quote, url, quote])
46

47 48 49 50 51 52

def replace_urls(text, staticfiles_prefix=None, replace_prefix='/static/'):
    def replace_url(static_url):
        return replace(static_url, staticfiles_prefix)

    return re.sub(r"""
53 54 55 56 57
        (?x)                 # flags=re.VERBOSE
        (?P<quote>\\?['"])   # the opening quotes
        (?P<prefix>{prefix}) # the prefix
        (?P<rest>.*?)        # everything else in the url
        (?P=quote)           # the first matching closing quote
58
        """.format(prefix=replace_prefix), replace_url, text)