When use subdomain in Flask, how to access static files quoted in css url and js files used require.js?

Viewed 414

Flask static settings:

app = Flask(__name__.split('.')[0], static_folder=None)
app.static_url_path = '/static'
app.static_folder = 'static'
app.add_url_rule(app.static_url_path + '/<path:filename>',
                 endpoint='static',
                 view_func=app.send_static_file)

CSS

@font-face {
    font-family: MuiiconSpread;
    font-weight: normal;
    font-style: normal;
    src:  url('../fonts/icons.ttf') format('truetype');
}

JS

require.config({
    paths: {
        'jquery': '/static/plugins/jquery-3.3.1/jquery.min',
    },
});

While access the subdomain such as: a.test.com, the icons.ttf and jquery.min.js are 404 error.

When I add subdomain='a' in add_url_rule for static, everything will be fine. But it just matches a.test.com, while access b.test.com should change the same config to subdomain='b'.

How to fix it?

1 Answers

I faced same issue.

Based on research, I understand that Flask-CORS is the best solution.

But for temporary fix, I have added below code in __init__.py file in the root folder.

@app.after_request
def after_request(response):
    if request.endpoint.startswith('static'):
        response.headers.add('Access-Control-Allow-Origin', '*')
    return response
Related