flask.blueprints Blueprint Example Code

A Blueprint in Flask is a "mold" or template for creating parts of web applications. This Blueprint class within the flask.blueprints module implements that functionality for Flask web apps.

Example 1 from CTFd

CTFd (homepage) is a capture the flag (CTF) hacking web app built with Flask. The application can be used as-is to run CTF events, or modified for custom rules for related scenarios. CTFd is open sourced under the Apache License 2.0.

CTFd / CTFd / auth.py

# auth.py
import base64

import requests
from flask import Blueprint, abort
from flask import current_app as app
from flask import redirect, render_template, request, session, url_for
from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired

from CTFd.cache import clear_team_session, clear_user_session
from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db
from CTFd.utils import config, email, get_app_config, get_config
from CTFd.utils import user as current_user
from CTFd.utils import validators
from CTFd.utils.config import is_teams_mode
from CTFd.utils.config.integrations import mlc_registration
from CTFd.utils.config.visibility import registration_visible
from CTFd.utils.crypto import verify_password
from CTFd.utils.decorators import ratelimit
from CTFd.utils.decorators.visibility import check_registration_visibility
from CTFd.utils.helpers import error_for, get_errors, markup
from CTFd.utils.logging import log
from CTFd.utils.modes import TEAMS_MODE
from CTFd.utils.security.auth import login_user, logout_user
from CTFd.utils.security.signing import unserialize
from CTFd.utils.validators import ValidationError

auth = Blueprint("auth", __name__)

@auth.route("/confirm", methods=["POST", "GET"])
@auth.route("/confirm/<data>", methods=["POST", "GET"])
@ratelimit(method="POST", limit=10, interval=60)
def confirm(data=None):
    if not get_config("verify_emails"):
        return redirect(url_for("challenges.listing"))

    if data and request.method == "GET":
            user_email = unserialize(data, max_age=1800)
        except (BadTimeSignature, SignatureExpired):
            return render_template(
                "confirm.html", errors=["Your confirmation link has expired"]
        except (BadSignature, TypeError, base64.binascii.Error):
            return render_template(
                "confirm.html", errors=["Your confirmation token is invalid"]

        user = Users.query.filter_by(email=user_email).first_or_404()
        if user.verified:
            return redirect(url_for("views.settings"))

## ... source file continues with no further Blueprint examples...

Example 2 from Flask AppBuilder

Flask-AppBuilder (documentation and example apps) is a web application generator that uses Flask to automatically create the code for database-driven applications based on parameters set by the user. The generated applications include default security settings, forms, and internationalization support.

Flask App Builder is provided under the BSD 3-Clause "New" or "Revised" license.

Flask AppBuilder / flask_appbuilder / base.py

# base.py
from functools import reduce
import logging
from typing import Dict

from flask import Blueprint, current_app, url_for

from . import __version__
from .api.manager import OpenApiManager
from .babel.manager import BabelManager
from .const import (
from .filters import TemplateFilters
from .menu import Menu, MenuApiManager
from .views import IndexView, UtilView

log = logging.getLogger(__name__)

def dynamic_class_import(class_path):
        tmp = class_path.split(".")
        module_path = ".".join(tmp[0:-1])

## ... source file abbreviated to get to Blueprint examples ...

    def app_name(self):
        return self.get_app.config["APP_NAME"]

    def app_theme(self):
        return self.get_app.config["APP_THEME"]

    def app_icon(self):
        return self.get_app.config["APP_ICON"]

    def languages(self):
        return self.get_app.config["LANGUAGES"]

    def version(self):
        return __version__

    def _add_global_filters(self):
        self.template_filters = TemplateFilters(self.get_app, self.sm)

    def _add_global_static(self):
        bp = Blueprint(

    def _add_admin_views(self):
        self.indexview = self._check_and_init(self.indexview)

    def _add_addon_views(self):
        for addon in self._addon_managers:
            addon_class = dynamic_class_import(addon)
            if addon_class:
                addon_class = addon_class(self)

## ... source file continues with no further Blueprint examples...

Example 3 from FlaskBB

FlaskBB (project website) is a Flask-based forum web application. The web app allows users to chat in an open message board or send private messages in plain text or Markdown.

FlaskBB is provided as open source under this license.

FlaskBB / flaskbb / auth / views.py

# views.py
import logging
from datetime import datetime

from flask import Blueprint, current_app, flash, g, redirect, request, url_for
from flask.views import MethodView
from flask_babelplus import gettext as _
from flask_login import (

from flaskbb.auth.forms import (
from flaskbb.extensions import db, limiter
from flaskbb.utils.helpers import (

## ... source file abbreviated to get to Blueprint examples ...

                except Exception:  # noqa
                    logger.exception("Database error while activating account")
                            "Could not activate account due to an unrecoverable error"  # noqa
                        ), "danger"

                    return redirect(url_for('auth.request_activation_token'))

                    _("Your account has been activated and you can now login."),
                return redirect(url_for("forum.index"))

        return render_template("auth/account_activation.html", form=form)

def flaskbb_load_blueprints(app):
    auth = Blueprint("auth", __name__)

    def login_rate_limit():
        return "{count}/{timeout}minutes".format(

    def login_rate_limit_message():
        current_limit = getattr(g, 'view_rate_limit', None)
        if current_limit is not None:
            window_stats = limiter.limiter.get_window_stats(*current_limit)
            reset_time = datetime.utcfromtimestamp(window_stats[0])
            timeout = reset_time - datetime.utcnow()
        return "{timeout}".format(timeout=format_timedelta(timeout))

    def check_rate_limiting():
        if not flaskbb_config["AUTH_RATELIMIT_ENABLED"]:
            return None
        return limiter.check()

    def login_rate_limit_error(error):
        return render_template(

## ... source file continues with no further Blueprint examples...

Example 4 from flask-base

flask-base (project documentation) provides boilerplate code for new Flask web apps. The purpose of the boilerplate is to stitch together disparate libraries that are commonly used in Flask projects, such as Redis for fast caching and transient data storage, SendGrid for transactional email, SQLAlchemy for persistent data storage through a relational database backend, Flask-WTF for form handling and many others.

flask-base is provided as open source under the MIT license.

flask-base / app / main / views.py

# views.py
from flask import Blueprint, render_template

from app.models import EditableHTML

main = Blueprint('main', __name__)

def index():
    return render_template('main/index.html')

def about():
    editable_html_obj = EditableHTML.get_editable_html('about')
    return render_template(
        'main/about.html', editable_html_obj=editable_html_obj)

## ... source file continues with no further Blueprint examples...

Example 5 from flask-bones

flask-bones (demo) is large scale Flask example application built with Blueprints (example Blueprint code). This project is provided as open source under the MIT license.

flask-bones / app / auth / init.py

# __init__.py
from flask import Blueprint

auth = Blueprint('auth', __name__, template_folder='templates')

from . import views

## ... source file continues with no further Blueprint examples...

Example 6 from flask-bookshelf

flask-bookshelf is the example Flask application that developers create when going through this Flask series of blog posts.

flask-bookshelf / bookshelf / admin / controllers.py

# controllers.py
from sqlalchemy import exc
from flask import Blueprint, render_template, flash
from flask import current_app, redirect, request, url_for
from flask_security.decorators import roles_required
from bookshelf.admin.forms.author_forms import CreateAuthorForm
from bookshelf.cache import cache
from bookshelf.data.models import Author, db

admin = Blueprint("admin", __name__, template_folder="templates")

def index():
    return render_template("admin_index.htm")

@admin.route("/author/create", methods=["GET", "POST"])
def create_author():
    form = CreateAuthorForm(request.form)
    if request.method == "POST" and form.validate():
        names = form.names.data
        current_app.logger.info("Adding a new author %s.", (names))
        author = Author(names)

            flash("Author successfully created.")
        except exc.SQLAlchemyError as e:
            flash("Author was not created.")

## ... source file continues with no further Blueprint examples...

Example 7 from Flask-Bootstrap

flask-bootstrap (PyPI package information) makes it easier to use the Bootstrap CSS framework in your Flask applications with less boilerplate code. The project was primarily created by Marc Brinkmann @mbr and the source code is open sourced under the Apache 2.0 license.

Flask-Bootstrap / flask_bootstrap / init.py

# __init__.py

import re

from flask import Blueprint, current_app, url_for

    from wtforms.fields import HiddenField
except ImportError:

    def is_hidden_field_filter(field):
        raise RuntimeError('WTForms is not installed.')

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

from .forms import render_form

__version__ = ''
BOOTSTRAP_VERSION = re.sub(r'^(\d+\.\d+\.\d+).*', r'\1', __version__)

class CDN(object):

## ... source file abbreviated to get to Blueprint examples ...

        filename = '%s.min.%s' % tuple(filename.rsplit('.', 1))

    cdns = current_app.extensions['bootstrap']['cdns']
    resource_url = cdns[cdn].get_resource_url(filename)

    if resource_url.startswith('//') and config['BOOTSTRAP_CDN_FORCE_SSL']:
        resource_url = 'https:%s' % resource_url

    return resource_url

class Bootstrap(object):
    def __init__(self, app=None):
        if app is not None:

    def init_app(self, app):
        app.config.setdefault('BOOTSTRAP_USE_MINIFIED', True)
        app.config.setdefault('BOOTSTRAP_CDN_FORCE_SSL', False)

        app.config.setdefault('BOOTSTRAP_QUERYSTRING_REVVING', True)
        app.config.setdefault('BOOTSTRAP_SERVE_LOCAL', False)

        app.config.setdefault('BOOTSTRAP_LOCAL_SUBDOMAIN', None)

        blueprint = Blueprint(
            static_url_path=app.static_url_path + '/bootstrap',



        app.jinja_env.globals['bootstrap_is_hidden_field'] =\
        app.jinja_env.globals['bootstrap_find_resource'] =\

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        local = StaticCDN('bootstrap.static', rev=True)
        static = StaticCDN()

        def lwrap(cdn, primary=static):

## ... source file continues with no further Blueprint examples...

Example 8 from flask-debugtoolbar

Flask Debug-toolbar (documentation and PyPI page) is a Flask conversion of the popular Django Debug Toolbar project. This extension creates a sidebar with useful debugging information when you are running a Flask application in development mode. The project is provided as open source under this license.

flask-debugtoolbar / flask_debugtoolbar / init.py

# __init__.py
import os
import warnings

from flask import Blueprint, current_app, request, g, send_from_directory, url_for
from flask.globals import _request_ctx_stack
from jinja2 import Environment, PackageLoader
from werkzeug.urls import url_quote_plus

from flask_debugtoolbar.compat import iteritems
from flask_debugtoolbar.toolbar import DebugToolbar
from flask_debugtoolbar.utils import decode_text, gzip_compress, gzip_decompress

    from importlib.metadata import version

    __version__ = version("Flask-DebugToolbar")
except ImportError:
    import pkg_resources

    __version__ = pkg_resources.get_distribution("Flask-DebugToolbar").version

module = Blueprint('debugtoolbar', __name__)

def replace_insensitive(string, target, replacement):
    no_case = string.lower()
    index = no_case.rfind(target.lower())
    if index >= 0:
        return string[:index] + replacement + string[index + len(target):]
    else:  # no results so return the original string
        return string

def _printable(value):
        return decode_text(repr(value))
    except Exception as e:
        return '<repr(%s) raised %s: %s>' % (
               object.__repr__(value), type(e).__name__, e)

class DebugToolbarExtension(object):
    _static_dir = os.path.realpath(
        os.path.join(os.path.dirname(__file__), 'static'))

    _redirect_codes = [301, 302, 303, 304]

## ... source file continues with no further Blueprint examples...

Example 9 from flask-restx

Flask RESTX is an extension that makes it easier to build RESTful APIs into your applications. Flask RESTX aims for minimal configuration to get basic APIs running for existing applications and it exposes endpoint documentation using Swagger.

Flask RESTX is provided as open source under the BSD 3-Clause license.

flask-restx / flask_restx / apidoc.py

# apidoc.py
from __future__ import unicode_literals

from flask import url_for, Blueprint, render_template

class Apidoc(Blueprint):

    def __init__(self, *args, **kwargs):
        self.registered = False
        super(Apidoc, self).__init__(*args, **kwargs)

    def register(self, *args, **kwargs):
        super(Apidoc, self).register(*args, **kwargs)
        self.registered = True

apidoc = Apidoc(

def swagger_static(filename):
    return url_for("restx_doc.static", filename=filename)

## ... source file continues with no further Blueprint examples...

Example 10 from Flask-WTF

Flask-WTF (project documentation and PyPI page) provides a bridge between Flask and the the WTForms form-handling library. It makes it easier to use WTForms by reducing boilerplate code and shorter examples for common form operations as well as common security practices such as CSRF.

Flask-WTF / flask_wtf / csrf.py

# csrf.py
import hashlib
import logging
import os
import warnings
from urllib.parse import urlparse
from functools import wraps

from flask import Blueprint, current_app, g, request, session
from itsdangerous import BadData, SignatureExpired, URLSafeTimedSerializer
from werkzeug.exceptions import BadRequest
from werkzeug.security import safe_str_cmp
from wtforms import ValidationError
from wtforms.csrf.core import CSRF

from ._compat import FlaskWTFDeprecationWarning

__all__ = ('generate_csrf', 'validate_csrf', 'CSRFProtect')
logger = logging.getLogger(__name__)

def generate_csrf(secret_key=None, token_key=None):

    secret_key = _get_config(
        secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
        message='A secret key is required to use CSRF.'
    field_name = _get_config(
        token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
        message='A field name is required to use CSRF.'

    if field_name not in g:

## ... source file abbreviated to get to Blueprint examples ...

        return None

    def protect(self):
        if request.method not in current_app.config['WTF_CSRF_METHODS']:

        except ValidationError as e:

        if request.is_secure and current_app.config['WTF_CSRF_SSL_STRICT']:
            if not request.referrer:
                self._error_response('The referrer header is missing.')

            good_referrer = f'https://{request.host}/'

            if not same_origin(request.referrer, good_referrer):
                self._error_response('The referrer does not match the host.')

        g.csrf_valid = True  # mark this request as CSRF valid

    def exempt(self, view):

        if isinstance(view, Blueprint):
            return view

        if isinstance(view, str):
            view_location = view
            view_location = '.'.join((view.__module__, view.__name__))

        return view

    def _error_response(self, reason):
        raise CSRFError(reason)

    def error_handler(self, view):

            '"@csrf.error_handler" is deprecated. Use the standard Flask '
            'error system with "@app.errorhandler(CSRFError)" instead. This '
            'will be removed in 1.0.'
        ), stacklevel=2)

        def handler(reason):

## ... source file continues with no further Blueprint examples...

Example 11 from Flask-User

Flask-User (PyPI information and project documentation) is a Flask extension that makes it easier to add custom user account management and authentication to the projects you are building. The extension supports persistent data storage through both relational databases and MongoDB. The project is provided as open source under the MIT license.

Flask-User / flask_user / user_manager.py

# user_manager.py

import datetime

from flask import abort, Blueprint, current_app, Flask, session
from flask_login import LoginManager
from wtforms import ValidationError

from . import ConfigError
from . import forms
from .db_manager import DBManager
from .email_manager import EmailManager
from .password_manager import PasswordManager
from .token_manager import TokenManager
from .translation_utils import lazy_gettext as _  # map _() to lazy_gettext()
from .user_manager__settings import UserManager__Settings
from .user_manager__utils import UserManager__Utils
from .user_manager__views import UserManager__Views

class UserManager(UserManager__Settings, UserManager__Utils, UserManager__Views):

    def __init__(self, app, db, UserClass, **kwargs):

        self.app = app
        if app:
            self.init_app(app, db, UserClass, **kwargs)

    def init_app(

## ... source file abbreviated to get to Blueprint examples ...

        def load_user_by_user_token(user_token):
            user = self.db_manager.UserClass.get_user_by_token(user_token)
            return user

        self.babel = app.extensions.get('babel', None)
        from .translation_utils import init_translations

        if not hasattr(app.jinja_env, 'install_gettext_callables'):

        def flask_user_context_processor():
            def call_or_get(function_or_property):
                return function_or_property() if callable(function_or_property) else function_or_property

            return dict(


        blueprint = Blueprint('flask_user', __name__, template_folder='templates')

        self.AddEmailFormClass = forms.AddEmailForm
        self.ChangePasswordFormClass = forms.ChangePasswordForm
        self.ChangeUsernameFormClass = forms.ChangeUsernameForm
        self.EditUserProfileFormClass = forms.EditUserProfileForm
        self.ForgotPasswordFormClass = forms.ForgotPasswordForm
        self.InviteUserFormClass = forms.InviteUserForm
        self.LoginFormClass = forms.LoginForm
        self.RegisterFormClass = forms.RegisterForm
        self.ResendEmailConfirmationFormClass = forms.ResendEmailConfirmationForm
        self.ResetPasswordFormClass = forms.ResetPasswordForm

        self.db_manager = DBManager(app, db, UserClass, UserEmailClass, UserInvitationClass, RoleClass)

        self.password_manager = PasswordManager(app)

        if self.USER_ENABLE_EMAIL:
            from .email_adapters.smtp_email_adapter import SMTPEmailAdapter
            self.email_adapter = SMTPEmailAdapter(app)

        if self.USER_ENABLE_EMAIL:
            self.email_manager = EmailManager(app)

## ... source file continues with no further Blueprint examples...

Example 12 from Flask-VueJs-Template

Flask-VueJs-Template (demo site) is a minimal Flask boilerplate starter project that combines Flask, Vue.js, and Flask-RESTPlus. The project provides some sensible defaults that are easy to continue building on, and the source code is open source under the MIT license.

Flask-VueJs-Template / app / client.py

# client.py

import os
from flask import Blueprint, render_template

client_bp = Blueprint('client_app', __name__,

## ... source file continues with no further Blueprint examples...

Example 13 from Datadog Flask Example App

The Datadog Flask example app contains many examples of the Flask core functions available to a developer using the web framework.

Datadog Flask Example App / python/flask/app / blueprint.py

# blueprint.py
from ddtrace import Pin
from flask import abort, Blueprint, render_template_string

from .limiter import limiter

bp = Blueprint('bp', __name__, url_prefix='/bp/')

Pin.override(bp, service='flask-bp', app='flask', app_type='web')

def bp_before_request():
    print('Hook: bp_before_request')

def bp_before_app_request():
    print('Hook: bp_before_app_request')

def bp_before_app_first_request():
    print('Hook: bp_before_app_first_request')

def bp_after_request(response):
    print('Hook: bp_after_request')
    return response

## ... source file continues with no further Blueprint examples...

Example 14 from tedivms-flask

tedivm's flask starter app is a base of Flask code and related projects such as Celery which provides a template to start your own Flask web app. The project comes baked with an admin panel, API authentication and authorization, SQLAlchemy and many other common libraries that are often used with Flask.

The project's code is provided as open source under the BSD 2-Clause "Simplified" license.

tedivms-flask / app / extensions / jinja.py

# jinja.py
from flask import Blueprint
from wtforms.fields import HiddenField
from jinja2 import evalcontextfilter, Markup
import re

jinja_extensions_blueprint = Blueprint('jinja_extensions_blueprint', __name__, template_folder='templates')

def filesize_format(num):
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    return '%.0f%s' % (num, ['', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][magnitude])

def is_hidden_field_filter(field):
    return isinstance(field, HiddenField)

def nl2br(eval_ctx, value):
    normalized_value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines
    html_value = normalized_value.replace('\n', '\n<br />\n')
    if eval_ctx.autoescape:
        return Markup(html_value)
    return html_value

## ... source file continues with no further Blueprint examples...

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2022