Modifying the response with Flask extensions
So, we have created an extension that adds new functionality to our templates. But how would we create an extension which modifies the behavior of our app at the request level? To demonstrate this, let's create an extension that modifies all the responses from Flask by compressing the contents of the response. This is a common practice in web development in order to speed up page load times, as compressing objects with a method like gzip is very fast and relatively cheap CPU-wise. Normally, this would be handled at the server level. So, unless you wish to host your app with only Python code, which is possible and will be covered in Chapter 13, Deploying Flask Apps, this extension really doesn't have much use in the real world.
To achieve this, we will use the gzip
module in the Python standard library to compress the contents after each request is processed. We will also have to add special HTTP headers into the response in order for...