简体   繁体   中英

How to compress a specific file using pipeline in Django?

I have many CSS files inside SITE_ROOT/sources/css and I want to compress only one file in SITE_ROOT/static/css using django-pipeline .

STATIC_ROOT = os.path.join(SITE_ROOT, 'static')

STATICFILES_DIRS = (
    os.path.join(SITE_ROOT, 'sources'),
)

PIPELINE_CSS = {
    'responsive': {
        'source_filenames': (
          'css/smartphones.css',
          'css/tablets.css',
        ),
        'output_filename': 'css/responsive.min.css',
    }
}

After running collectstatic I see in the static/ folder the minified file (responsive.min.css) but there is also a copy of all files located in the sources/ folder and a copy of django admin static files. How can I get only the minified file in the STATIC_ROOT folder?

You can create your own STATICFILES_STORAGE class, inherited from PipelineStorage , which expand the behavior of PipelineMixin . Something like this (need to be tested):

import shutil
import os.path

from django.conf import settings
from pipeline.storage import PipelineStorage

class PipelineCleanerStorage(PipelineStorage):
    def post_process(self, paths, dry_run=False, **options):
        # Do the usual stuff (compress and deliver)
        res = PipelineStorage.post_process(self, paths, dry_run=False, **options)

        # Clean sources files there
        shutil.rmtree(os.path.join(settings.BASE_DIR, "static/sources"))

        yield res

and use it in your settings.py instead of PipelineStorage .

Another way could be to run an automated task to clean this directory after each collectstatic. It would be the same idea but on the manage command itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM