How to remove older css files after webassets rebuilds the scss for a python flask app?

133 Views Asked by At

I have a Python 3.9 flask app which uses the flask_assets library.

My flask init.py file looks like:

import logging
import os
from flask import Flask, request, current_app
from config import Config
from flask_assets import Environment
from app.utils.assets import bundles

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    assets = Environment(app)
    assets.debug = True
    assets.versions = 'timestamp'
    # assets.cache = False

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)
    assets.register(bundles)

    if not app.debug and not app.testing:
        app.logger.setLevel(logging.INFO)
        app.logger.info('Application starting.')

    return app

Since flask_assets is built on top of webassets, I import the Environment and a css Bundle I created which compiles my scss code to css.

Here is how my Bundle looks like:

from flask_assets import Bundle

bundles = {
    'css': Bundle (
        'scss/_main.scss',
        'scss/_base.scss',
        'scss/_typography.scss',
        'scss/_page_home.scss',
        'scss/_page_technote.scss',
        filters='pyscss',
        depends=('**/*.scss'),
        output='css/style.%(version)s.scss.css'
    )
}

The problem I have:

Every time I make a change to my scss files, the css successfully rebuilds with a new version for cache busting. However, the older css files remain.

What's the best automatic way to remove them every time a rebuild happens? Is there any reason for keeping the older files?

Also - side question - is it possible for the Bundle object to automatically consider all files of certain type in a directory? Rather than me listing every file individually?

Here is how my files look like:

enter image description here

Thank you!

1

There are 1 best solutions below

0
On

You can use rmtree. Even though I believe a better way exists, this does it.

from os.path import join
from shutil import rmtree

app = Flask(__name__)

rmtree(join(app.static_folder, 'css'), ignore_errors=True)

You can improve this by checking the file meta by date or similar to not delete the unchanged ones.