Book Image

Mastering Flask

By : Jack Stouffer
Book Image

Mastering Flask

By: Jack Stouffer

Overview of this book

Starting from a simple Flask app, this book will walk through advanced topics while providing practical examples of the lessons learned. After building a simple Flask app, a proper app structure is demonstrated by transforming the app to use a Model-View-Controller (MVC) architecture. With a scalable structure in hand, the next chapters use Flask extensions to provide extra functionality to the app, including user login and registration, NoSQL querying, a REST API, an admin interface, and more. Next, you’ll discover how to use unit testing to take the guesswork away from making sure the code is performing as it should. The book closes with a discussion of the different platforms that are available to deploy a Flask app on, the pros and cons of each one, and how to deploy on each one.
Table of Contents (20 chapters)
Mastering Flask
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 the browser...