Subresource Integrity for Django
Maintained. Last release 2 months ago, commits in 2 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install django-sriDjango SRI
Subresource Integrity for Django.
Installation
pip install django-sri
And add sri to your INSTALLED_APPS.
Usage
Template Tags
django-sri is intended to primarily be used through template tags:
{% load sri %}
<!-- Add the required integrity attributes to the relevant tag -->
<link rel="stylesheet" href="{% static 'index.css' %}" {% sri_attrs 'index.css' %} />
<script src="{% static 'index.js %}" {% sri_attrs 'index.js' %}></script>
<!-- Or, get the integrity value directly -->
<script src="{% static 'index.js %}" integrity="{% sri_integrity 'index.js' %}" crossorigin="anonymous"></script>
<link rel="stylesheet" href="{% static 'index.css' %}" integrity="{% sri_integrity 'index.css' %}" crossorigin="anonymous" />
Note: By default, sri_attrs does not output when DEBUG is True, as static files change a lot during local development. To override this, set USE_SRI to True. sri_integrity always outputs.
When outside DEBUG (or forced using USE_SRI), hashes are cached using an lru_cache.
Algorithms
The SRI standard supports 3 algorithms: SHA256, SHA384 and SHA512. By default, SHA256 is used. To override this, supply an additional algorithm argument to the template tag:
{% load sri %}
{% sri_integrity "index.js" algorithm="sha512" %} <!-- Will output "integrity='sha512-...'" -->
The default algorithm can be changed by setting SRI_ALGORITHM to the required algorithm.
API
Outside of templates, the relevant integrity values can be retrieved using get_sri or get_sri_of_static.