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<\/code> , 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>
There's no need to change how you link to static files, you can still use url_for('static', filename='myfile.txt')<\/code> .
Replace the default static view with one that redirects to the CDN if it is 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)
This flask cdn integration guide<\/a> may be worth taking a read through. Basically you can install the Flask-CDN extension<\/a> and define your CDN URL within your app.py file like so:
from flask import Flask
from flask.ext.cdn import CDN
app = Flask(__name__)
app.config['CDN_DOMAIN'] = 'cdn.yourdomain.com'
CDN(app)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.