全局覆盖 url_for 以便扩展程序也使用它

Nix*_*xon 5 python flask flask-assets

我正在尝试url_for全局覆盖该函数。我想这样做,以便我可以从多个网址加载我的资源,以克服浏览器的最大并发连接数限制。

我曾经app.context_processor在模板中替换我自己的函数,但与 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)
Run Code Online (Sandbox Code Playgroud)

在模板中,url_for可以正常工作,但ASSET_URL不能。

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)
Run Code Online (Sandbox Code Playgroud)

如何在 Flask-Assets 等扩展中实现此功能?