I've got the following flask route which serves static content:
@app.route('/static/<path:path>')
@resourceDecorator
def getStaticFile(path):
return send_from_directory('static', path)
@resourceDecorator
is declared as follows:
def resourceDecorator(f):
def new_func(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
resp.cache_control.no_cache = True # Turn off caching
resp.headers['Access-Control-Allow-Origin'] = '*' # Add header to allow CORS
return resp
return update_wrapper(new_func, f)
The decorator sets headers to deactivate caching and allow cross domain access. This works for my other, "regular" routes, but the files sent through the static route do not seem to get their headers set.
What's going wrong here?
To reference the static files using the url_for() function, pass in the name of the directory – static in this case – and the keyword argument of filename= followed by your static file name. Flask automatically creates a static view that serves static files from a folder named static in your application's directory.
Static files in Flask have a special route. All application URLs that begin with "/static", by convention, are served from a folder located at "/static" inside your application's root folder.
Headers is class within the flask. app module of the Flask web framework that is imported from the datastructures module of the Werkzeug project. Headers handles the HTTP headers from requests and responses for Flask web applications.
For static files, flask sets the default cache timeout to 12 hours/43200s hence your problem. You can change the default cache timeout in send_from_directory
by passing the cache_timeout
value directly since it uses the send_file
function to send a file to a client.
send_from_directory(cache_timeout=0)
Alternatively you can override the get_send_file_max_age
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With