Using Django pipeline to add hash to static files

Time:2021-3-26

Using Django pipeline to add hash to static files

Why do I need hash static files?

LookHow to develop and deploy front end code in large companies?Zhang Yunlong’s answer.

In this way, when the static file has been modified, it will be very convenient to get the latest modified version, while the unmodified static file will still use the cache. This avoids the embarrassment of not updating the user’s static files after modification, and can make full use of the cache.

demo

django_pipeline_demo

install

sudo mkdir /opt/projects
git clone https://github.com/duoduo369/django_pipeline_demo.git
cd django_pipeline_demo
ln -s $(pwd) /opt/projects
ln -s /opt/projects/django_pipeline_demo/deploy/nginx/django_pipeline.conf /etc/nginx/sites-enabled
pip install -r requirements.txt
python manage.py runserver 0.0.0.0:9888
nginx -s reload
VIM / etc / hosts add 127.0.0.1:9888 Django_ pipline_ demo.com

Django’s Library pipeline

mako, django-mako, django-pipeline-demo

The effect is this, todjango_pipeline_demoFor example.

Let’s talk about the final usage first

  1. Debug must be false (online is false). If it is true, Django will be used to find static files by default instead of pipeline.
  2. python manage.py collectstatic
  3. Restart Django project

Key code explanation

settings.py Several configurations of,
How to install and configure Django pipeline, please move tofile.

Explain several collection related configurations

# python  manage.py  After collectstatic, the file will be thrown to static_ Under root
STATIC_ROOT = './statics'

#Django's templates will be found in these directories
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

#When developing, collectstatic will look up the path of CSS and then drop it to static_ Under root
#After using pipeline, hash code, such as CSS, will be added to the static file/ index.css
#After collectstatic, it will become CSS/ index.as1df14jah8dfh .css
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static_dev"),
)

templates/common/static_pipeline.html

This is to define a URL with Mako. After static files are imported with this URL, the hash version can be found.

<%!
from django.contrib.staticfiles.storage import staticfiles_storage
%>

<%def name='url(file)'><%
try:
    url = staticfiles_storage.url(file)
except:
    url = file
%>${url}</%def>

index.html

First, import / common / static_ pipeline.html , where static files need to be referenced${ static.url ('unhash file path ')}

<%namespace name='static' file='/common/static_pipeline.html'/>
....
    <link rel="stylesheet" href="${static.url('css/index.css')}" type="text/css" media="all" />
....