5

I'm trying to override the url_for function globally. I want to do this so that I can load my assets from multiple urls to overcome the browser's maximum concurrent connections limit.

I used app.context_processor to substitute my own function in templates, but it's not working when used with Flask-Assets.

STATIC_URLS = [
    static.1.domain.com,
    static.2.domain.com,
    static.3.domain.com
]

@app.context_processor
def override_url_for():
    return dict(url_for=static_urls)

def static_urls(endpoint, **values):
    if endpoint == 'static':
        filename = values.get('filename', None)
        static_urls = app.config.get('STATIC_URLS', None)
        if filename and static_urls:
            hashed = int(hashlib.md5(filename.encode()).hexdigest(), 16)
            index = hashed % len(static_urls) - 1
            url = static_urls[index]
            url = app.url_map.bind(url)
            return url.build(endpoint, values=values, force_external=True)

    return url_for(endpoint, **values)

In the template, url_for works correctly, but ASSET_URL does not.

{{ url_for('static', filename='style.css') }}
http://static.1.domain.com/static/style.css

{% assets 'style' %}
<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">
{% endassets %}
http://domain.com/static/style.css

How can I make this work in extensions like Flask-Assets?

davidism
  • 121,510
  • 29
  • 395
  • 339
Nixxxon
  • 158
  • 1
  • 9
  • You can see how Flask-CDN does it: https://github.com/wichitacode/flask-cdn/blob/master/flask_cdn.py#L7 – nathancahill May 16 '15 at 21:53
  • Instead of monkey patching the function globally, they override it in `jinja_env` so it will only work in templates. But since it's static files that might be what you want? – nathancahill May 16 '15 at 21:54
  • My current solution already works in templates but not when using the external plugin Flask-Assets – Nixxxon May 16 '15 at 21:58
  • @nathancahill Your link doesn't work and I wanted to check it out. Does it have a typo in it? – Dave Scotese Nov 27 '18 at 22:46
  • @DaveScotese Looks like the author of that repo deleted his Github account in the last 4 years. We'll never know what was there. – nathancahill Nov 27 '18 at 23:07
  • It might have been something like this: https://github.com/e-dard/flask-s3/blob/b8c72b40eb38a05135eec36a90f1ee0c96248f72/flask_s3.py#L132 – nathancahill Nov 27 '18 at 23:09

0 Answers0