网站JS,CSS等静态资源文件对于访问量大的网站来说不仅浪费带宽,而且也影响网站的访问速度。django-compressor 可以将静态文件压缩合并成一个文件,不仅减少了网站的请求次数,还能节省网络带宽
安装django_compressor
For windows
$ pip install wheel==0.29.0
$ pip install rcssmin==1.0.6 --install-option="--without-c-extensions"
$ pip install rjsmin==1.0.12 --install-option="--without-c-extensions"
$ pipinstall django_compressor==2.0
For Ubuntu:
$ pip install django_compressor==2.0
在Django项目中添加 Django-Compressor
Django-Compressor 开启与否取决于DEBUG参数,默认是COMPRESS_ENABLED与DEBUG的值相反。因为Django-Compressor的功能本身是用在生产环境下项目发布前对静态文件压缩处理的。因此想在开发阶段(DEBUG=True)的时候做测试使用,需要手动设置COMPRESS_ENABLED=True
# 默认状态 COMPRESS_ENABLED=False,因为生产环境 DEBUG=False
# 只有在生产环境才有压缩静态资源的需求
# 如果是开发环境就主动开启压缩功能、开启手动压缩功能
if DEBUG:
COMPRESS_ENABLED = True # 开启压缩功能
COMPRESS_OFFLINE = True # 开启手动压缩
else:
DEBUG_PROPAGATE_EXCEPTIONS = True
INSTALLED_APPS = (
# other apps
"compressor",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
'compressor.finders.CompressorFinder',)
<!--需要引入静态文件的文件顶部load compress -->
{% load compress %}
{% compress css %}
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
<!--其它css文件-->
{% endcompress %}
{% compress js %}
<script src="{% static "js/jquery-1.10.2.js" %}"></script>
<!--其它js文件-->
{% endcompress %}
# 可以收集项目下的所有的静态资源包括settings.py引入的第三方应用使用的静态文件,一般使用nginx托管静态文件的话,这里还是收集一下,全部使用项目下的static静态文件资源夹
$ python manage.py collectstatic
# 如果需要在本地压缩,需要在settings.py中添加 COMPRESS_OFFLINE=True才能执行下边命令手动压缩
$ python manage.py compress
压缩后页面效果
# 压缩后页面加载静态文件
<link rel="stylesheet" href="/static/CACHE/css/f18b10165eed.css" type="text/css">
<script type="text/javascript" src="/static/CACHE/js/9d1f64ba50fc.js"></script>
参考文章:https://www.cnblogs.com/skying555/p/5972735.html
转载请注明: StormSha » Django 静态文件加速