static_replace.py 961 Bytes
Newer Older
1 2 3 4
from staticfiles.storage import staticfiles_storage
import re


5 6 7 8 9 10
def replace(static_url, prefix=None):
    if prefix is None:
        prefix = ''
    else:
        prefix = prefix + '/'

11
    quote = static_url.group('quote')
12 13 14 15 16
    if staticfiles_storage.exists(static_url.group('rest')):
        return static_url.group(0)
    else:
        url = staticfiles_storage.url(prefix + static_url.group('rest'))
        return "".join([quote, url, quote])
17

18 19 20 21 22 23

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"""
24 25 26 27 28
        (?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
29
        """.format(prefix=replace_prefix), replace_url, text)