Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Cache-Control header to my static files hosted on Heroku?

Tags:

django

heroku

I want to enable browser caching of images, css and java script files.

https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers

The heroku article says this in its conclusion:

"Once the concepts behind HTTP caching are understood the next step is to implement them in your application. Most modern web frameworks make this a trivial task."

Can someone tell me how to do this trivial task? I have a django-python app.

like image 623
Sai Krishna Avatar asked Oct 24 '25 15:10

Sai Krishna


1 Answers

Your static resources should really be served from a webserver such as nginx or apache and not directly from django but to answer your question, django inlcudes a staticfiles app which one assumes you are using to manage those resources, if so, use

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'

in your settings.py file to enable django's caching for staticfiles.

c.f https://docs.djangoproject.com/en/1.6/ref/contrib/staticfiles/#cachedstaticfilesstorage https://docs.djangoproject.com/en/1.7/ref/contrib/staticfiles/#cachedstaticfilesstorage

[the 1.6 link has more explanation of how this works]

For caching as a whole in django, I recommend reading https://docs.djangoproject.com/en/1.7/topics/cache/ where you can see how to use middleware for site level caching or the cache_control decorator for view-caching like so:

from django.views.decorators.cache import cache_control

@cache_control(must_revalidate=True, max_age=3600) def my_view(request): # ...

like image 106
io2 Avatar answered Oct 26 '25 04:10

io2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!