Review of Flask Web Development – O’Reilly book

flask web development miguel grinberg oreilly

Author: Miguel Grinberg

Title: Flask Web Development – Second edition

Editorial: O’Reilly

Year: 2018

nº pages: 250

Estimated read time: 40 days

Review of the book: Flask Web Development

This book is a key player to show how to develop web applications based on one of the best web frameworks in Python, Flask web framework.

The main success key of Flask framework is that can be build up using different extensions and plugins to build your own app with the needs that each project requires. So in contrast with other frameworks, this is build from ground up, with no assumptions of the developers/project needs and it is highly integrate into a more complex projects.

This book is one of the best sellers books about Flask becuase it shows in deep many important aspects of the web development and mainly focused on Flask web development.

Book structure

This book has 3 main parts:

  • Getting started: it is an overview of the web framework, how to get it installed and how to deal with the book’s code that will be used along the book reading.
  • In deep explanation of the sample application: the main application of the book is based on a book with a following system. In this sectino of the book, the author explains all the details of the application and the essential components.
  • Show case of useful tools on web development in Flask: it shows the main use cases of many useful technologies used for the web development in flask such how to write tests, how to deal with code coverage or how to deploy into different environments.

Key learning concepts from Flask Web Development

I have extracted the key points found on the book and explained them in the following sections.

Flask app structure and flask app config

On the book it is proposing an app layout structure to set up each folder and file belonging to a project. This scaffold helps to integrate different topics such static files, migrations folder, templates or tests into any flask app.

Further more, the it shows how to integrate the configuration of a flask application to support different environments (dev, staging and production) in an easy and scalable way.

This is the resultant layout of any flask app proposed in the book:


Users management in Flask

It shows a way to manage users in flask with 3 different areas:

  • Users: each user has a username, email, name and some permissions managed by roles.
  • Permissions: it explains how to manage the user permissions using a bit mask to do operations such addition of each permission just adding a new permission on a mathematical way.
  • Roles: the way to manage a pack of permissions is made by signing a role to a set of permissions, and that role is again signed then to a user.
class Permission:
    FOLLOW = 1
    COMMENT = 2
    WRITE = 4
    MODERATE = 8
    ADMIN = 16

......... Checking permissions .........
    def add_permission(self, perm):
        if not self.has_permission(perm):
            self.permissions += perm

    def remove_permission(self, perm):
        if self.has_permission(perm):
            self.permissions -= perm

    def reset_permissions(self):
        self.permissions = 0

    def has_permission(self, perm):
        return self.permissions & perm == perm

Also it explains other packages to extend the functionality related with users in flask:

  • Flask-Login: handling of users login.
  • Werkzeug: verification and creation of secure passwords.
  • itsdangerous: security and verification of tokens.
  • Flask-Mail: email handling to authenticate, reset and confirm user emails.
class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User', backref='role', lazy='dynamic')

Request Response pattern en Flask

The book explains how to deal with the pattern request-response in flask:

  • Routing and endpoint definitions.
  • Error handling and acceptance of HTTP methods.
  • Request context.
  • Flask internal variables and the context of each one such: request, g, current_app or current_user.
  • Response of requests via HTML response or JSON.

Dealing with forms and templates in flask

The use of forms and how to render templates on a web framework is one key feature and it is explained with:

  • How to render using Jinja2.
  • Extending templates, applying filters and developing macros for jinja.
  • Showing content on the templates.
  • Forms handling using Flask-WTF (What the forms).
  • Visual improvements and integration of bootstrap with WTF using Flask-bootstrap.

Data bases and migrations using SQLAlchemy & alembic in Flask

Database management and migrations:

  • Storing data into a relational database using Flask-SQLAlchemy as an ORM for Flask.
  • Database migrations using Alembic and SQLALchemy.
  • Managing data using a shell to add data manually and static content from files.
  • Creation of data samples for testing using faker.
  • Usage of different database configurations depending on the environment, dev -> sqlite, staging and prod different MySQL databases.
from random import randint
from sqlalchemy.exc import IntegrityError
from faker import Faker
from . import db
from .models import User, Post

def users(count=100):
    fake = Faker()
    i = 0
    while i < count:
        u = User(,
            i += 1
        except IntegrityError:

Sample blog app in flask and extensions

Along the book, the author is explaining in deep the sample blog application and how to develop each individual part, covering the next topics:

  • User management.
  • Markdown support to show user posts on a good format.
  • User answers of each post.
  • Comments administration based on roles and permissions.
  • System to follow/unfollow users to show different timelines.

Also, on the last part of the book, it is included topics such code coverage, app profiler, testing and deployment of applications in flask.

Creation of APIs web in Flask

It is briefly show how to implement an API to connect other applications or do request from the front-end into the sample application.

It explains how to add a proper version to make the system scalable and good practices on how to deal with the APIs in general.

Deployment of flask applications

At the last pieces of the book, the reader can find how to deploy the application on multiple ways and platforms:

  • Deployment of flask applications at Heroku.
  • Flask applications and deployment using Docker
  • Traditional deployment using gunicorn (or waitress for windows) and nginx or apache on a dedicated machine.
class HerokuConfig(ProductionConfig):
    SSL_REDIRECT = True if os.environ.get('DYNO') else False

    def init_app(cls, app):

        # handle reverse proxy server headers
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)

        # log to stderr
        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()

Miguel Grinberg books

Recommended books to learn Python

This is a list of recommended books to learn Python, how to program, data types, algorithms and much more.

Disponible en:


Leave a Reply

Your email address will not be published.

Ver más

  • Responsable: Oscar Ramirez.
  • Finalidad:  Moderar los comentarios.
  • Legitimación:  Por consentimiento del interesado.
  • Destinatarios y encargados de tratamiento: No se ceden o comunican datos a terceros para prestar este servicio. El Titular ha contratado los servicios de alojamiento web a ionos (1&1) que actúa como encargado de tratamiento.
  • Derechos: Acceder, rectificar y suprimir los datos.
  • Información Adicional: Puede consultar la información detallada en la Política de Privacidad.

Post comment