4

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?

4

0 回答 0