Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress a specific file using pipeline in Django?

Tags:

python

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?

like image 998
Mustapha Aoussar Avatar asked Nov 01 '22 00:11

Mustapha Aoussar


1 Answers

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.

like image 121
Maxime Lorant Avatar answered Nov 14 '22 06:11

Maxime Lorant