Skip to main content

The best way to build Flask apps

Project description

Flask Unchained

The best way to build Flask apps

What is it?

Flask Unchained is a (work-in-progress) fully integrated, optional-batteries-included web framework built on top of Flask and its extension ecosystem. Flask Unchained aims to be a fresh, modern take on building web apps and APIs with Flask - while trying to stay as true as possible to the spirit and API of Flask.


  • designed to be easy to start with and even easier to grow your app
  • clean, predictable application structure that encourages good design patterns (no circular imports!)
  • documented with real-world-usage in mind (some sections are still a work-in-progress)
  • no integration headaches between supported libraries; everything just works
  • absolutely as little boilerplate as possible (your focus should be on your app, not plumbing!)
  • out-of-the-box support for testing with pytest
  • simple and consistent patterns for customizing, extending, and/or overriding almost everything (e.g. configuration, views/controllers/resources, routes, templates, services, extensions, ...)
    • your customizations are easily distributable as a standalone bundle (Python package), which itself then supports the same patterns for customization, ad infinitum.


Flask Unchained implements the Application Factory Pattern, utilizing a standardized (but configurable) way to organize "bundles" of code, such that they become easily distributable, reusable, and customizable across multiple independent projects. All of the code within bundles is automatically discovered and registered with the app. You can think of bundles as an enhanced replacement for both Flask blueprints and extensions. Bundles are somewhat comparable to Django's "apps", but I think you'll find bundles are more powerful and flexible.

The architecture is inspired by Symfony, which is enterprise-level awesome, aside from the fact that it isn't Python ;) If you've heard of Laravel, that framework is built on top of the Symfony Components - with Flask Unchained, the existing Flask/Python ecosystems constitute our "components".[*]

[*] Don't like the default choices? Flask Unchained is almost completely customizable. The core architecture offers you the potential to use an entirely different stack of libraries, or swap out only certain components - the power to choose is yours.

Useful Links

Table of Contents


  • Python 3.6+
  • improved class-based views with the Controller, Resource, and ModelResource base classes
  • declarative routing
  • dependency injection of services and extensions
  • includes out-of-the-box (mostly optional) integrations with:
    • SQLAlchemy and Flask-Migrate (database ORM and migrations, optional). SQLAlchemy Unchained builds some "sugar" on top of SQLAlchemy to make the best ORM in existence even quicker and easier to use:
      • models automatically get a primary key column, unless you define one yourself
      • models are (optionally) automatically timestamped when they are created and updated
      • super-simple polymorphic model class inheritance
      • a unified API for creating, querying, updating and deleting models with the ModelManager service base class
    • Flask-Login (user authentication and sessions management) and Flask-Principal (user authorization with permissions and roles)
      • both session and token authentication are currently supported
      • includes optional support for registration (with optional required email confirmation before account activation)
      • optional change password and forgot password functionality
    • Flask-Marshmallow (SQLAlchemy model serialization, optional)
      • the API Bundle provides a (work-in-progress) RESTful API framework integrating Marshmallow Serializers (aka Schemas) and SQLAlchemy models using ModelResource
      • work-in-progress support for OpenAPI (aka Swagger) docs, using ReDoc as the frontend
    • Flask-GraphQL (GraphQL support, integrates Graphene with SQLAlchemy, optional)
    • Flask-WTF (forms and CSRF protection, always enabled)
    • Flask-Session (server-side sessions, optional)
    • Celery (distributed task queue, optional)
    • Flask-Mail (email sending support, optional)
    • Flask-Admin (admin interface, optional)
    • Flask-BabelEx (translations, always enabled but optional)
    • pytest and factory_boy (testing framework)


# (create a virtual environment)
pip install flask-unchained[dev]
flask new project <your-project-folder-name>

# (answer the questions and `cd` into the new directory)
pip install -r requirements-dev.txt
flask run

NOTE: If you enabled the SQLAlchemy Bundle, then you may need to run migrations before running the development server:

flask db init
flask db migrate -m 'create initial tables'
flask db upgrade

What does it look like?

Application Structure and Project Layout

Unlike stock Flask, Flask Unchained apps cannot be written in a single file. Instead, Flask Unchained's bundles define a (configurable) folder convention that must be followed for Flask Unchained to be able to correctly discover all of your code. A large application structure might look about like this:

├── app                 # your app bundle package
│   ├── admins          # model admins
│   ├── commands        # Click CLI groups/commands
│   ├── extensions      # Flask extensions
│   ├── models          # SQLAlchemy models
│   ├── fixtures        # SQLAlchemy model fixtures (for seeding the dev db)
│   ├── serializers     # Marshmallow serializers (aka schemas)
│   ├── services        # dependency-injectable services
│   ├── tasks           # Celery tasks
│   ├── templates       # Jinja2 templates
│   ├── views           # Controllers, Resources and views
│   └──
│   └──       # app config
│   └──       # declarative routes
├── assets              # static assets to be handled by Webpack
│   ├── images
│   ├── scripts
│   └── styles
├── bundles             # custom bundles and/or bundle extensions/overrides
│   └── security        # a customized/extended Security Bundle
│       ├── models
│       ├── serializers
│       ├── services
│       ├── templates
│       └──
├── db
│   └── migrations      # Alembic (SQLAlchemy) migrations (generated by Flask-Migrate)
├── static              # static assets (Webpack compiles to here, and Flask
│                       #  serves this folder at /static (by default))
├── templates           # the top-level templates folder
├── tests               # your pytest tests
├── webpack             # Webpack configs
└── # the Flask Unchained config

To learn how to build such a larger example application, check out the official tutorial.

A minimal application structure looks about like this:

├── app
│   ├── templates
│   │   └── site
│   │       └── index.html
│   ├──
│   ├──
│   ├──
│   ├──
│   ├──
│   ├──
│   └──

Let's built it!

# (create a virtualenv and activate it)
pip install flask-unchained[dev,sqlalchemy] \
   && mkdir -p hello-flask-unchained/app && cd hello-flask-unchained \
   && touch && cd app \
   && mkdir -p templates/site && touch templates/site/index.html \
   && touch


The first step is to create an app bundle module in your project root - we're calling ours app here - with an AppBundle subclass in it:

# hello-flask-unchained/app/

from flask_unchained import AppBundle, FlaskUnchained

class App(AppBundle):
    # you only need to subclass AppBundle; everything below is optional. for example, these
    # attributes can be set to customize which bundle module to load from (defaults shown)
    config_module_name = 'config'
    models_module_name = 'models'
    routes_module_name = 'routes'
    services_module_name = 'services'

    # these two methods are optional callbacks which the app factory will call
    def before_init_app(self, app: FlaskUnchained):

    def after_init_app(self, app: FlaskUnchained):


The configuration for Flask Unchained itself is pretty minimal, for example:

# hello-flask-unchained/

import os

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

def folder_or_none(folder_name):
    folder = os.path.join(PROJECT_ROOT, folder_name)
    return folder if os.path.exists(folder) else None

# these get passed to the :class:`FlaskUnchained` constructor
TEMPLATE_FOLDER = folder_or_none('templates')
STATIC_FOLDER = folder_or_none('static')
STATIC_URL_PATH = '/static' if STATIC_FOLDER else None

# declare which bundles Flask Unchained should load
    'app',  # your app bundle *must* be last

And add the required app configuration to your app bundle:

# hello-flask-unchained/app/

import os

from flask_unchained import AppBundleConfig

class Config(AppBundleConfig):
    SECRET_KEY = os.getenv('FLASK_SECRET_KEY', 'change-me-to-a-secret-key')

# the following env-specific config classes are all optional

class DevConfig(Config):

class ProdConfig(Config):

class StagingConfig(ProdConfig):


# hello-flask-unchained/app/

from flask_unchained.bundles.sqlalchemy import db

class NameSubmission(db.Model):
    class Meta:
        repr = ('id', 'name')

    name = db.Column(db.String(128))

    # the following primary key and timestamp columns are automatically added to models
    # (if necessary/not customized)
    # id = db.Column(db.Integer, primary_key=True)
    # created_at = db.Column(db.DateTime,
    # updated_at = db.Column(db.DateTime,,


# hello-flask-unchained/app/

from flask_unchained.bundles.sqlalchemy import ModelManager

from . import models

class NameSubmissionManager(ModelManager):
    class Meta:
        model = models.NameSubmission

    def create(self, name, commit: bool = False, **kwargs) -> models.NameSubmission:
        return super().create(name=name, commit=commit, **kwargs)


# hello-flask-unchained/app/

from flask_unchained.bundles.sqlalchemy.forms import ModelForm

from . import models

class NameSubmissionForm(ModelForm):
    class Meta:
        model = models.NameSubmission


A hello world view:

# hello-flask-unchained/app/

from flask_unchained import Controller, route, request, injectable, param_converter

from . import forms, models, services

class SiteController(Controller):
    name_submission_manager: services.NameSubmissionManager = injectable

    @route('/', methods=['GET', 'POST'])
    @param_converter(id=models.NameSubmission)  # converts the `id` query param to a model
    def index(self, name_submission=None):
        form = forms.NameSubmissionForm(request.form)
        if form.validate_on_submit():
            name_submission = self.name_submission_manager.create(,
            return self.redirect('index',
        return self.render('index', form=form, name_submission=name_submission)


{# hello-flask-unchained/app/templates/layout.html #}

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>{% block title %}Flask Unchained Hello World{% endblock %}</title>

    {% block stylesheets %}
    {% endblock stylesheets %}

    {% block body %}
      <div class="container">
        {% block content %}
        {% endblock content %}
    {% endblock body %}

    {% block javascripts %}
    {% endblock javascripts %}
{# hello-flask-unchained/app/templates/site/index.html #}

{% extends 'layout.html' %}

{% set name = | default('World') %}

{% block title %}Hello {{ name }}{% endblock %}

{% block content %}
  <h1>Hello {{ name }}</h1>

  <form name="{{ form._name }}" action="{{ url_for('site_controller.index') }}" method="POST">
    {{ form.hidden_tag() }}
    {{'Enter your name:') }}
    {{ }}
    <button type="submit">Submit</button>
{% endblock %}


Now we can register the controller with our routes:

# hello-flask-unchained/app/

from flask_unchained import (controller, resource, func, include, prefix,
                             get, delete, post, patch, put, rule)

from .views import SiteController

routes = lambda: [


And run it:

flask run
 * Environment: development
 * Debug mode: on
 * Running on (Press CTRL+C to quit)

Now you should be able to browse to http://localhost:5000 to view your new site!


Contributions are more than welcome! This is a big project with a lot of different things that need doing. There's a TODO file in the project root, or if you've got an idea, open an issue or a PR and let's chat.



Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for Flask-Unchained, version 0.7.1
Filename, size File type Python version Upload date Hashes
Filename, size Flask_Unchained-0.7.1-py3-none-any.whl (420.6 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size Flask Unchained-0.7.1.tar.gz (297.2 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page