Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library – Flask-Minify.
Advantages of Minification
- Websites load faster as fewer lines are there to upload and download.
- Bandwidth cost is reduced as less data is flown over the network.
- Decompression is not needed before usage.
- As the site loads faster, UX and SEO improve as well.
To install this module type the below command in the terminal.
pip install Flask-Minify
Function Used: minify(self, app=None, html=True, js=True, cssless=True, fail_safe=True, bypass=, passive=False, static=True, script_types=)
- app: Flask app instance to be initiated.
- js: Minify js or not.
- cssless: Minify css or not.
- fail_safe: To avoid raising error while minifying.
- bypass: List of endpoints to bypass minifying.
- passive: to selectively minify routes
- static: To enable minifying static files css, less and js.
- script_types: List of script types to limit js minification to.
Step 1: Importing libraries and initializing Minify with app context.
Step 2: Adding route, output HTML with minified code.
Step 3 : Running application
Example 2: Applying minification to some routes
In this, we can perform minification on only required routes not all, as per requirements. This is done by passing “passive=True” while passing context.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course