Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Set header on static files

Tags:

python

flask

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?

like image 739
zxz Avatar asked Oct 30 '15 07:10

zxz


People also ask

How do I set a static path on a Flask?

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.

Where is Flask static folder?

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.

What are headers in Flask?

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.


1 Answers

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.

like image 184
simanacci Avatar answered Oct 16 '22 17:10

simanacci