There is no need to change the way static files are referenced, you can still use url_for('static', filename='myfile.txt') . Replace the default static view with the one that redirects to the CDN, if configured.
from urllib.parse import urljoin # or for python 2: from urlparse import urljoin from flask import redirect @app.endpoint('static') def static(filename): static_url = app.config.get('STATIC_URL') if static_url: return redirect(urljoin(static_url, filename)) return app.send_static_file(filename)
Regardless of whether you work on the developer's computer or on STATIC_URL , set STATIC_URL configuration to CDN, and requests for static files will be redirected there.
Redirects are relatively cheap and remembered by browsers. If you get to the point where they will significantly affect performance, you can write a function that communicates directly when using CDN.
@app.template_global() def static_url(filename): static_url = app.config.get('STATIC_URL') if static_url: return urljoin(static_url, filename) return url_for('static', filename=filename)
The template_global decorator makes the function available in all templates. Use it instead of url_for when you need links for static files.
There may be a Flask extension that already does this for you. For example, Flask-S3 provides url_for which serves static files from AWS S3.
davidism
source share