Serve static files from a CDN rather than Flask in production

Viewed 6681

In my Flask app I serve the static assets through the app in the dev env, but I'd like to use a CDN in production. Every asset is loaded in a template called base.html, so I guess the easiest solution is to pass a variable to the render function and use it in the template like:

<script src="{{ STATIC_URL }}/js/main.js"></script>

Normally it would be an empty string in the dev env, and the cdn url in production. I'd like to avoid passing this STATIC_URL variable to every view. I could make it work with

@bp.context_processor
def set_static_path():
    return dict(STATIC_URL='https://foo.bar.com')

But for me this seems a little hacky. Is there a better way to solve this problem?

3 Answers

I had a similar problem using Flask Assets and Flask-CDN. I found that Flask-CDN was trying and failing to generate timestamps for each asset. Upon failure it would revert to relative URLs.

Adding app.config['CDN_TIMESTAMP'] = False fixed the issue.

Related