File hash GET parameters for Django staticfiles

jieforest發表於2012-08-03
About
A class for the static files app in Django that invalidates outdated browser cache.

How to use
You add the line

CODE:

STATICFILES_STORAGE = 'path.to.hashpathstaticfilesstorage.HashPathStaticFilesStorage'to your settings.py and everywhere you use the 'static' templatetag it will append a hash calculated form. the contents of the file as a GET parameter at the end of the URL for the file. Example:

CODE:

{% static "path/to/file.txt" %} -> /static/path/to/file.txt?4e1243

This guarantees that every time you update your static files, whether it is an image, a CSS file or anything else, all browsers fetch the new version of the file instead of using their cached versions.

Remember to change the import path to match your setup (replace the 'path.to' with your actual import path).

[b]Caching[/b]

You can reduce the time it takes to return the URL by caching the hashes when they are first calculated. The cache framework that ships with Django is used to store the hashes, so make sure you configure that before caching your hashes.

When you start using the cache, and every time after that when you have to invalidate the cache, you simply create an object of the type HashPathStaticFilesStorage and call the method 'invalidate_cache' on that object:

[code]
h = HashPathStaticFilesStorage()
h.invalidate_cache()
[/code]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-739707/,如需轉載,請註明出處,否則將追究法律責任。

相關文章