24

I'm trying to set a reasonable cache expiry for my JS files while in development. I have the standard setup, where HTML, CSS and JS are living under the static directory.

The docs do mention this, but for the life of me I cannot get this to work. I've tried both methods implied, first

class MyFlask(flask.Flask):
    def get_send_file_max_age(self, name):
        if name.lower().endswith('.js'):
            return 60
        return flask.Flask.get_send_file_max_age(self, name)

app = MyFlask(__name__)

and

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 60

Both have had no effect, my JS files under /static are still coming back with the default cache timeout,

Cache-Control: public, max-age=43200

Any pointers appreciated.

5
  • 5
    1. Do you use the flask dev server or a http proxy like nginx? 2. You should use return super(MyFlask, self).get_send_file_max_age(name) instead of return flask.Flask.get_send_file_max_age(self, name). Commented Jul 24, 2012 at 10:01
  • The above class works for me, using the defualt flask development server. Commented Nov 28, 2012 at 20:17
  • For these and performance reasons i (and from what i've heard many others) let my static files be directly served by whatever webserver (nginx/apache) i am using. Commented Jun 21, 2013 at 13:30
  • @Jarus Sorry for the slow reply (2 years). This was the dev server only. I don't think I ever resolved this, and shortly afterward stopped using Flask (unrelated reasons). Thanks for your input all the same. Commented Aug 2, 2014 at 9:30
  • for those arriving here later... this answer to a related question may help. You can modify the cache control headers sent by Flask using the "cache_control" collection on the Response object. See the documentation here Commented May 10, 2020 at 17:39

2 Answers 2

1

You may want to look at webassets to manage the cache expiry. It works in both development and production environment.

Sign up to request clarification or add additional context in comments.

Comments

1

I had this problem and couldn't find an answer online that worked for me.

Then I realised that my static files are not being served from Flask at all! Flask only generates my HTML. The static files are served directly by my web server (Apache in my case, yours might be Nginx or something else).

Here are the instructions for Apache.

First install the mod_expires module:

sudo a2enmod expires

Then add something like this to your .htaccess file:

ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/* "access plus 1 year"

More details on how to configure it in the Apache manual.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.