How to point Flask static to Amazon S3 URLs? How to point Flask static to Amazon S3 URLs? flask flask

How to point Flask static to Amazon S3 URLs?


If you are using any of the static_* options to the Flask object, it is assuming that it'll be responsible for serving those files. A static route is configured that serves both as the view to serve the static files and as the url_for() target to generate the URLs.

So, with Flask alone, you'd have to replace all url_for('static', ...) calls with hardcoded URLs to your CDN instead.

Instead, you should switch to using Flask-CDN, a handy Flask add-on to handle seamless switching between static files hosted by Flask and by a CDN:

from flask_cdn import CDNapp = Flask(__name__)cdn = CDN(app)

and set the CDN_DOMAIN configuration option to http://my-bucket.s3.amazonaws.com when deploying to production.

In debug mode, url_for() will then generate the old /static/.. urls for Flask to handle, in production mode, url_for() prefixes those urls with the CDN_DOMAIN value. If the latter is left to the default None setting, no such URL alterations take place, making it possible to run Flask locally with debug switched off as needed.

Note that the behaviour of url_for() is only altered for Jinja templates; if you need to generate static URLs in your views, you'll have to swap flask.url_for() out for flask_cdn.url_for().