Sunday, February 4, 2024

How to switch between minified and non-minified javascript/css/html in Flask (Python)?

You can separate your development (human readable) and deployment (minified) files into distinct folders, as illustrated below:

source/
├─ static/
├─ static_dev/
├─ templates/
├─ templates_dev/
...

In your Python code, make your Flask app use the root URL as a static path:

app = Flask(__name__, static_url_path="")

You can switch between development and deployment folders based on your environment or global variable. That really depends on your system and your preferences, so the following code assumes that variable check is abstracted by a function:

if is_development_environment():
    app.static_folder   = "static_dev"
    app.template_folder = "templates_dev"

I am often using Google App engine for my own projects, so the code in my case is:

if not os.getenv("GAE_ENV", "").startswith("standard"):
    ...

Finally, you need to instruct your minify scripts to pick source files from development folders and use deployment folders as output destination. Also make sure that only deployment folders are uploaded to your server, and that they are ignored by your source code control system. 

In my case, I need to add the following two lines to .gitignore:

/static/
/templates/
And the following to .gcloudignore:
/static_dev
/templates_dev

Let me know if you are interested in ant script that does copying/minifying.

No comments:

Post a Comment