flask.app Flask Example Code

Flask is a class within the flask.app module of the Flask framework that implements the WSGI application specification. This class acts as a central registry for a significant amount of a Flask application's functionality, including URL rounting, template configurations, and handling view functions.

BadRequest, Headers, and ImmutableDict are several other callables with code examples from the same flask.app package.

You should read up on these subjects along with these Flask examples:

Example 1 from Braintree Flask app

Braintree's Flask example payments app demonstrates how to incorporate this payment provider's API into your Flask web application. The code is open sourced under the MIT license.

Braintree Flask app / app.py

# app.py
from flask import Flask, redirect, url_for, render_template, request, flash

import os
from os.path import join, dirname
from dotenv import load_dotenv
import braintree
from gateway import generate_client_token, transact, find_transaction


app = Flask(__name__)
app.secret_key = os.environ.get('APP_SECRET_KEY')

PORT = int(os.environ.get('PORT', 4567))


@app.route('/', methods=['GET'])
def index():
    return redirect(url_for('new_checkout'))

@app.route('/checkouts/new', methods=['GET'])
def new_checkout():
    client_token = generate_client_token()
    return render_template('checkouts/new.html', client_token=client_token)

@app.route('/checkouts/<transaction_id>', methods=['GET'])

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

Example 2 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 / tests / test_themes.py

# test_themes.py

import os
import shutil

import pytest
from flask import render_template, render_template_string, request
from jinja2.exceptions import TemplateNotFound
from jinja2.sandbox import SecurityError
from werkzeug.test import Client

from CTFd.config import TestingConfig
from CTFd.utils import get_config, set_config
from tests.helpers import create_ctfd, destroy_ctfd, gen_user, login_as_user

def test_themes_run_in_sandbox():
    app = create_ctfd()
    with app.app_context():
                "{{ ().__class__.__bases__[0].__subclasses__()[40]('./test_utils.py').read() }}"
        except SecurityError:
        except Exception as e:
            raise e

def test_themes_cant_access_configpy_attributes():
    app = create_ctfd()
    with app.app_context():
        assert app.config["SECRET_KEY"] == "AAAAAAAAAAAAAAAAAAAA"
        assert (
            app.jinja_env.from_string("{{ get_config('SECRET_KEY') }}").render()

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

            r = client.get("/challenges")
            assert r.status_code == 200
            assert "Challenges" in r.get_data(as_text=True)

            r = client.get("/scoreboard")
            assert r.status_code == 200
            assert "Scoreboard" in r.get_data(as_text=True)

def test_that_request_path_hijacking_works_properly():
    app = create_ctfd(setup=False, application_root="/ctf")
    assert app.request_class.__name__ == "CTFdRequest"
    with app.app_context():
        with app.test_request_context("/challenges"):
            assert request.path == "/ctf/challenges"

    app = create_ctfd()
    assert app.request_class.__name__ == "CTFdRequest"
    with app.app_context():
        with app.test_request_context("/challenges"):
            assert request.path == "/challenges"

        from flask import Flask

        test_app = Flask("test")
        assert test_app.request_class.__name__ == "Request"
        with test_app.test_request_context("/challenges"):
            assert request.path == "/challenges"

def test_theme_fallback_config():

    class ThemeFallbackConfig(TestingConfig):
        THEME_FALLBACK = False

    app = create_ctfd(config=ThemeFallbackConfig)
        os.mkdir(os.path.join(app.root_path, "themes", "foo_fallback"))
    except OSError:

    with app.app_context():
        app.config["THEME_FALLBACK"] = False
        set_config("ctf_theme", "foo_fallback")
        assert app.config["THEME_FALLBACK"] == False
        with app.test_client() as client:
                r = client.get("/")

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

Example 3 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 / tests / test_fab_cli.py

# test_fab_cli.py
import glob
import json
import logging
import os
import tempfile

from click.testing import CliRunner
from flask import Flask
from flask_appbuilder import AppBuilder, SQLA
from flask_appbuilder.cli import (

from .base import FABTestCase

log = logging.getLogger(__name__)

APP_DIR = "myapp"

class FlaskTestCase(FABTestCase):
    def setUp(self):

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

            self.assertIn("User bob created.", result.output)

            result = runner.invoke(list_users, [])
            self.assertIn("bob", result.output)

            runner.invoke(create_permissions, [])

            runner.invoke(reset_password, ["--username=bob", "--password=bar"])

    def test_list_views(self):
        os.environ["FLASK_APP"] = "app:app"
        runner = CliRunner()
        with runner.isolated_filesystem():
            result = runner.invoke(list_views, [])
            self.assertIn("List of registered views", result.output)
            self.assertIn(" Route:/api/v1/security", result.output)

class SQLAlchemyImportExportTestCase(FABTestCase):
    def setUp(self):
        with open("flask_appbuilder/tests/data/roles.json", "r") as fd:
            self.expected_roles = json.loads(fd.read())

    def test_export_roles(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            app = Flask("src_app")
            ] = f"sqlite:///{os.path.join(tmp_dir, 'src.db')}"
            db = SQLA(app)
            app_builder = AppBuilder(app, db.session)  # noqa: F841
            cli_runner = app.test_cli_runner()

            path = os.path.join(tmp_dir, "roles.json")

            export_result = cli_runner.invoke(export_roles, [f"--path={path}"])

            self.assertEqual(export_result.exit_code, 0)

            with open(path, "r") as fd:
                resulting_roles = json.loads(fd.read())

            for expected_role in self.expected_roles:
                match = [
                    r for r in resulting_roles if r["name"] == expected_role["name"]
                resulting_role = match[0]
                resulting_role_permission_view_menus = {
                    (pvm["permission"]["name"], pvm["view_menu"]["name"])
                    for pvm in resulting_role["permissions"]
                expected_role_permission_view_menus = {
                    (pvm["permission"]["name"], pvm["view_menu"]["name"])
                    for pvm in expected_role["permissions"]

    def test_export_roles_filename(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            app = Flask("src_app")

            ] = f"sqlite:///{os.path.join(tmp_dir, 'src.db')}"
            db = SQLA(app)
            app_builder = AppBuilder(app, db.session)  # noqa: F841

            owd = os.getcwd()
            cli_runner = app.test_cli_runner()
            export_result = cli_runner.invoke(export_roles)

            self.assertEqual(export_result.exit_code, 0)
                len(glob.glob(os.path.join(tmp_dir, "roles_export_*"))), 0

    def test_import_roles(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            app = Flask("dst_app")
            ] = f"sqlite:///{os.path.join(tmp_dir, 'dst.db')}"
            db = SQLA(app)
            app_builder = AppBuilder(app, db.session)
            cli_runner = app.test_cli_runner()

            path = os.path.join(tmp_dir, "roles.json")

            with open(path, "w") as fd:

            self.assertEqual(len(app_builder.sm.get_all_roles()), 2)

            import_result = cli_runner.invoke(import_roles, [f"--path={path}"])
            self.assertEqual(import_result.exit_code, 0)

            resulting_roles = app_builder.sm.get_all_roles()

            for expected_role in self.expected_roles:
                match = [r for r in resulting_roles if r.name == expected_role["name"]]
                resulting_role = match[0]

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

Example 4 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 / app.py

# app.py
import logging
import logging.config
import os
import sys
import time
import warnings
from datetime import datetime

from flask import Flask, request
from flask_login import current_user
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.exc import OperationalError, ProgrammingError

from flaskbb.extensions import (alembic, allows, babel, cache, celery, csrf,
                                db, debugtoolbar, limiter, login_manager, mail,
                                redis_store, themes, whooshee)
from flaskbb.plugins import spec
from flaskbb.plugins.manager import FlaskBBPluginManager
from flaskbb.plugins.models import PluginRegistry
from flaskbb.plugins.utils import remove_zombie_plugins_from_db, template_hook
from flaskbb.user.models import Guest, User
from flaskbb.utils.helpers import (app_config_from_env, crop_title,
                                   format_date, format_time, format_datetime,
                                   forum_is_unread, get_alembic_locations,
                                   get_flaskbb_config, is_online, mark_online,
                                   render_template, time_since, time_utcnow,
from flaskbb.utils.requirements import (CanBanUser, CanEditUser, IsAdmin,
                                        IsAtleastModerator, can_delete_topic,
                                        can_edit_post, can_moderate,
                                        can_post_reply, can_post_topic,
from flaskbb.utils.search import (ForumWhoosheer, PostWhoosheer,
                                  TopicWhoosheer, UserWhoosheer)
from flaskbb.utils.settings import flaskbb_config
from flaskbb.utils.translations import FlaskBBDomain

from . import markup  # noqa
from .auth import views as auth_views  # noqa
from .deprecation import FlaskBBDeprecation
from .display.navigation import NavigationContentType
from .forum import views as forum_views  # noqa
from .management import views as management_views  # noqa
from .user import views as user_views  # noqa

logger = logging.getLogger(__name__)

def create_app(config=None, instance_path=None):

    app = Flask(
        "flaskbb", instance_path=instance_path, instance_relative_config=True

    if not os.path.exists(app.instance_path):

    configure_app(app, config)
    configure_celery_app(app, celery)
    app.pluggy.hook.flaskbb_additional_setup(app=app, pluggy=app.pluggy)

    return app

def configure_app(app, config):

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

Example 5 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 / init.py

# __init__.py
import os

from flask import Flask
from flask_assets import Environment
from flask_compress import Compress
from flask_login import LoginManager
from flask_mail import Mail
from flask_rq import RQ
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect

from app.assets import app_css, app_js, vendor_css, vendor_js
from config import config as Config

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

mail = Mail()
db = SQLAlchemy()
csrf = CSRFProtect()
compress = Compress()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'account.login'

def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')




    from .utils import register_template_utils

    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))

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

Example 6 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 / init.py

# __init__.py
import time

from flask import Flask, g, render_template, request
import arrow
import requests

from app import config
from app.assets import assets
from app.auth import auth
from app.commands import create_db, drop_db, populate_db, recreate_db
from app.database import db
from app.extensions import lm, travis, mail, migrate, bcrypt, babel, rq, limiter
from app.user import user
from app.utils import url_for_other_page

def create_app(config=config.base_config):
    app = Flask(__name__)


    def get_locale():
        return request.accept_languages.best_match(config.SUPPORTED_LOCALES)

    if babel.locale_selector_func is None:
        babel.locale_selector_func = get_locale

    def before_request():
        g.request_start_time = time.time()
        g.request_time = lambda: '%.5fs' % (time.time() - g.request_start_time)
        g.pjax = 'X-PJAX' in request.headers

    @app.route('/', methods=['GET'])
    def index():
        return render_template('index.html')

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

Example 7 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 / init.py

# __init__.py
from flask import abort, Flask, g, render_template, request, current_app
from flask_babel import Babel
from flask_security import current_user
from bookshelf.utils import get_instance_folder_path
from bookshelf.main.controllers import main
from bookshelf.admin.controllers import admin
from bookshelf.cache import cache
from bookshelf.config import configure_app
from bookshelf.data.models import db

app = Flask(

babel = Babel(app)

def set_language_code(endpoint, values):
    if "lang_code" in values or not g.get("lang_code", None):
    if app.url_map.is_endpoint_expecting(endpoint, "lang_code"):
        values["lang_code"] = g.lang_code

def get_lang_code(endpoint, values):
    if values is not None:

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

Example 8 from flaskex

Flaskex is a working example Flask web application intended as a base to build your own applications upon. The application comes with pre-built sign up, log in and related screens, as well as a database backend. Flaskex is provided as open source under the MIT license.

flaskex / app.py

# app.py

from scripts import tabledef
from scripts import forms
from scripts import helpers
from flask import Flask, redirect, url_for, render_template, request, session
import json
import sys
import os

app = Flask(__name__)
app.secret_key = os.urandom(12)  # Generic key for dev purposes only

@app.route('/', methods=['GET', 'POST'])
def login():
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                if helpers.credentials_valid(username, password):
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Login successful'})
                return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    user = helpers.get_user()
    return render_template('home.html', user=user)

def logout():

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

Example 9 from Flask-HTTPAuth

Flask-HTTPAuth (documentation and PyPI package information) is a Flask framework extension that creates Basic and Digest HTTP authentication for routes. This project is primarily built and maintained by Miguel Grinberg. It is provided as open source under the MIT license.

Flask-HTTPAuth / tests / test_basic_get_password.py

# test_basic_get_password.py
import unittest
import base64
from flask import Flask
from flask_httpauth import HTTPBasicAuth

class HTTPAuthTestCase(unittest.TestCase):
    def setUp(self):
        app = Flask(__name__)
        app.config['SECRET_KEY'] = 'my secret'

        basic_auth = HTTPBasicAuth()

        def get_basic_password(username):
            if username == 'john':
                return 'hello'
            elif username == 'susan':
                return 'bye'
                return None

        def index():
            return 'index'

        def basic_auth_route():
            return 'basic_auth:' + basic_auth.username()

        self.app = app
        self.basic_auth = basic_auth

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

Example 10 from flask-phone-input

flask-phone-input is an example application that ties together the intTellInput.js JavaScript plugin with the Flask-WTF form-handling library. flask-phone-input is provided as open source under the MIT license.

flask-phone-input / app.py

# app.py
from flask import Flask, render_template, session, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
import phonenumbers
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, ValidationError

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'

class PhoneForm(FlaskForm):
    phone = StringField('Phone', validators=[DataRequired()])
    submit = SubmitField('Submit')

    def validate_phone(self, phone):
            p = phonenumbers.parse(phone.data)
            if not phonenumbers.is_valid_number(p):
                raise ValueError()
        except (phonenumbers.phonenumberutil.NumberParseException, ValueError):
            raise ValidationError('Invalid phone number')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = PhoneForm()
    if form.validate_on_submit():
        session['phone'] = form.phone.data
        return redirect(url_for('show_phone'))
    return render_template('index.html', form=form)

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

Example 11 from flaskSaaS

flaskSaas is a boilerplate starter project to build a software-as-a-service (SaaS) web application in Flask, with Stripe for billing. The boilerplate relies on many common Flask extensions such as Flask-WTF, Flask-Login, Flask-Admin, and many others. The project is provided as open source under the MIT license.

flaskSaaS / app / init.py

# __init__.py
from flask import Flask

app = Flask(__name__)


from app.logger_setup import logger

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

from flask.ext.mail import Mail
mail = Mail(app)

from flask_debugtoolbar import DebugToolbarExtension
app.config['DEBUG_TB_PROFILER_ENABLED'] = True
toolbar = DebugToolbarExtension(app)

from flask.ext.bcrypt import Bcrypt
bcrypt = Bcrypt(app)

from app.views import main, user, error

from flask.ext.login import LoginManager
from app.models import User

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

Example 12 from Flask-Security-Too

Flask-Security-Too (PyPi page and project documentation) is a maintained fork of the original Flask-Security project that makes it easier to add common security features to Flask web applications. A few of the critical goals of the Flask-Security-Too project are ensuring JavaScript client-based single-page applications (SPAs) can work securely with Flask-based backends and that guidance by the OWASP organization is followed by default.

The Flask-Security-Too project is provided as open source under the MIT license.

Flask-Security-Too / flask_security / utils.py

# utils.py
from flask.json import JSONEncoder
from flask_login import login_user as _login_user
from flask_login import logout_user as _logout_user
from flask_login import current_user
from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME
from flask_principal import AnonymousIdentity, Identity, identity_changed, Need
from flask_wtf import csrf
from wtforms import ValidationError
from itsdangerous import BadSignature, SignatureExpired
from werkzeug import __version__ as werkzeug_version
from werkzeug.local import LocalProxy
from werkzeug.datastructures import MultiDict

from .quart_compat import best, get_quart_status
from .proxies import _security, _datastore, _pwd_context, _hashing_context
from .signals import user_authenticated

if t.TYPE_CHECKING:  # pragma: no cover
    from flask import Flask, Response
    from .datastore import User

SB = t.Union[str, bytes]

localize_callback = LocalProxy(lambda: _security.i18n_domain.gettext)

FsPermNeed = partial(Need, "fsperm")
FsPermNeed.__doc__ = """A need with the method preset to `"fsperm"`."""

def _(translate):
    return translate

def get_request_attr(name: str) -> t.Any:
    return getattr(_request_ctx_stack.top, name, None)

def set_request_attr(name, value):
    return setattr(_request_ctx_stack.top, name, value)

if get_quart_status():  # pragma: no cover

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

Example 13 from Flask-SocketIO

Flask-SocketIO (PyPI package information, official tutorial and project documentation) is a code library by Miguel Grinberg that provides Socket.IO integration for Flask applications. This extension makes it easier to add bi-directional communications on the web via the WebSockets protocol.

The Flask-SocketIO project is open source under the MIT license.

Flask-SocketIO / test_socketio.py

# test_socketio.py
import json
import unittest
import coverage

cov = coverage.coverage(branch=True)

from flask import Flask, session, request, json as flask_json
from flask_socketio import SocketIO, send, emit, join_room, leave_room, \
    Namespace, disconnect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app)
disconnected = None

def on_connect():
    if request.args.get('fail'):
        return False
    send(json.dumps({h: request.headers[h] for h in request.headers.keys()
                     if h not in ['Host', 'Content-Type', 'Content-Length']}))

def on_disconnect():
    global disconnected
    disconnected = '/'

def connect():

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

        client.emit('exit', {}, namespace='/ns')
        with self.assertRaises(RuntimeError):
            client.emit('hello', {}, namespace='/ns')

    def test_emit_class_based(self):
        client = socketio.test_client(app, namespace='/ns')
        client.emit('my_custom_event', {'a': 'b'}, namespace='/ns')
        received = client.get_received('/ns')
        self.assertEqual(len(received), 1)
        self.assertEqual(len(received[0]['args']), 1)
        self.assertEqual(received[0]['name'], 'my custom response')
        self.assertEqual(received[0]['args'][0]['a'], 'b')

    def test_request_event_data_class_based(self):
        client = socketio.test_client(app, namespace='/ns')
        global request_event_data
        request_event_data = None
        client.emit('other_custom_event', 'foo', namespace='/ns')
        expected_data = {'message': 'other_custom_event', 'args': ('foo',)}
        self.assertEqual(request_event_data, expected_data)

    def test_delayed_init(self):
        app = Flask(__name__)
        socketio = SocketIO(allow_upgrades=False, json=flask_json)

        def on_connect():
            send({'connected': 'foo'}, json=True)

        socketio.init_app(app, cookie='foo')
        self.assertEqual(socketio.server.eio.cookie, 'foo')

        client = socketio.test_client(app)
        received = client.get_received()
        self.assertEqual(len(received), 1)
        self.assertEqual(received[0]['args'], {'connected': 'foo'})

    def test_encode_decode(self):
        client = socketio.test_client(app)
        data = {'foo': 'bar', 'invalid': socketio}
        self.assertRaises(TypeError, client.emit, 'my custom event', data,
        data = {'foo': 'bar'}
        ack = client.emit('my custom event', data, callback=True)
        data['foo'] = 'baz'

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

Example 14 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(
        self, app, db, UserClass,
        RoleClass=None,    # Only used for testing

        if not isinstance(app, Flask):
            raise TypeError("flask_user.UserManager.init_app(): Parameter 'app' is an instance of class '%s' "
                            "instead of a subclass of class 'flask.Flask'."
                            % app.__class__.__name__)

        app.user_manager = self

        self.db = db

        for attrib_name in dir(self):
            if attrib_name[0:5] == 'USER_':
                default_value = getattr(UserManager, attrib_name)
                setattr(self, attrib_name, app.config.get(attrib_name, default_value))

        if not self.USER_EMAIL_SENDER_EMAIL:
            default_sender = app.config.get('DEFAULT_MAIL_SENDER', None)
            default_sender = app.config.get('MAIL_DEFAULT_SENDER', default_sender)
            if default_sender:
                if default_sender[-1:] == '>':
                    start = default_sender.rfind('<')
                    if start >= 1:
                        self.USER_EMAIL_SENDER_EMAIL = default_sender[start + 1:-1]
                        if not self.USER_EMAIL_SENDER_NAME:
                            self.USER_EMAIL_SENDER_NAME = default_sender[0:start].strip(' "')

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

Example 15 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 / init.py

# __init__.py
import os
from flask import Flask, current_app, send_file

from .api import api_bp
from .client import client_bp

app = Flask(__name__, static_folder='../dist/static')

from .config import Config
app.logger.info('>>> {}'.format(Config.FLASK_ENV))

def index_client():
    dist_dir = current_app.config['DIST_DIR']
    entry = os.path.join(dist_dir, 'index.html')
    return send_file(entry)

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

Example 16 from Flasky

Flasky is a wonderful example application by Miguel Grinberg that he builds while teaching developers how to use Flask in his books and videos. Flasky is open sourced under the MIT license.

Flasky / app / init.py

# __init__.py
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_pagedown import PageDown
from config import config

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
pagedown = PageDown()

login_manager = LoginManager()
login_manager.login_view = 'auth.login'

def create_app(config_name):
    app = Flask(__name__)


    if app.config['SSL_REDIRECT']:
        from flask_sslify import SSLify
        sslify = SSLify(app)

    from .main import main as main_blueprint

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/v1')

    return app

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

Example 17 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 / app.py

# app.py
from ddtrace import patch_all; patch_all(flask=True, requests=True)  # noqa

from ddtrace import tracer

from flask import Flask, Response
from flask import after_this_request
from flask import abort, jsonify, render_template, url_for
from flask.views import View
from werkzeug.routing import Rule

from flask_caching import Cache
from flask_cors import CORS

import requests

from .blueprint import bp
from .exceptions import AppException
from .limiter import limiter
from .signals import connect_signals

app = Flask(__name__)



Cache(app, config=dict(CACHE_TYPE='simple'))

def inject_url_map():
    return dict(url_map=app.url_map)

def before_first_request():
    print('Hook: before_first_request')

def before_request():
    print('Hook: before_request')

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

Example 18 from keras-flask-deploy-webapp

The keras-flask-deploy-webapp project combines the Flask web framework with the Keras deep learning library to provide an example image classifier that is easy to deploy. The application can be quckly run in a Docker container on your local development environment. The project is licensed under the GNU General Public License v3.0.

keras-flask-deploy-webapp / app.py

# app.py
import os
import sys

from flask import Flask, redirect, url_for, request, render_template, Response, jsonify, redirect
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer

import tensorflow as tf
from tensorflow import keras

from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image

import numpy as np
from util import base64_to_pil

app = Flask(__name__)

from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
model = MobileNetV2(weights='imagenet')

print('Model loaded. Check')

MODEL_PATH = 'models/your_model.h5'

def model_predict(img, model):
    img = img.resize((224, 224))

    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)

    x = preprocess_input(x, mode='tf')

    preds = model.predict(x)
    return preds

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

Example 19 from sandman2

sandman2 (project documentation and PyPI package information) is a code library for automatically generating RESTful APIs from existing database schemas. This approach is handy for solving straightforward situations where you want to put an abstraction layer between one or more applications and your relational database to prevent or reduce direct database access.

The sandman2 project is provided under the Apache License 2.0.

sandman2 / sandman2 / app.py

# app.py

from flask import Flask, current_app, jsonify
from sqlalchemy.sql import sqltypes

from sandman2.exception import (
from sandman2.service import Service
from sandman2.model import db, Model, AutomapModel
from sandman2.admin import CustomAdminView
from flask_admin import Admin
from flask_httpauth import HTTPBasicAuth

auth = HTTPBasicAuth()

def get_app(
    app = Flask('sandman2')
    app.config['SQLALCHEMY_DATABASE_URI'] = database_uri
    app.config['SANDMAN2_READ_ONLY'] = read_only
    app.classes = []
    admin = Admin(app, base_template='layout.html', template_mode='bootstrap3')
    if user_models:
        with app.app_context():
            _register_user_models(user_models, admin, schema=schema)
    elif reflect_all:
        with app.app_context():
            _reflect_all(exclude_tables, admin, read_only, schema=schema)

    def index():
        routes = {}
        for cls in app.classes:
            routes[cls.__model__.__name__] = '{}{{/{}}}'.format(
        return jsonify(routes)
    return app

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

Example 20 from Science Flask

Science Flask is a Flask-powered web application for online scientific research tools. The project was built as a template for any scientist or groups of scientists to use when working together without having to really understand how the application is built. The application includes an academic registration process (only valid academic email addresses can be used), an admin panel, logging, and analysis forms.

@danielhomola is the primary creator of Science Flask and the project is open source under the GNU General Public License.

Science Flask / frontend / init.py

# __init__.py
import os
from flask import Flask, url_for, redirect, request, abort
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_security import Security, SQLAlchemyUserDatastore, signals, \
import flask_admin
from flask_admin.contrib import sqla
from flask_admin import helpers as admin_helpers
from flask_wtf.csrf import CSRFProtect
from celery import Celery

appdir = os.path.abspath(os.path.dirname(__file__))
ROOTDIR = os.path.abspath(os.path.join(appdir, os.pardir))
user_data_folder = os.path.join(ROOTDIR, 'userData')

app = Flask(__name__, instance_path=user_data_folder)


db = SQLAlchemy(app)

mail = Mail(app)

csrf = CSRFProtect(app)

def create_celery_app():
    celery = Celery(__name__, broker=app.config['CELERY_BROKER_URL'])
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    celery.app = app
    return celery

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

Example 21 from ShortMe

ShortMe is a Flask app that creates a shortened URL that redirects to another, typically much longer, URL. The project is provided as open source under the MIT license.

ShortMe / app / setup / setup.py

# setup.py
import os

from flask import Flask
from flask_restful import Api
from dotenv import load_dotenv

from app.server.db.extensions import db
from app.server.db.models import AuthToken
from app.server.routes.index import index_blueprint
from app.server.routes.internal.redirect_to_url import redirect_to_url_blueprint
from app.server.routes.internal.favicon import app_blueprint
from app.server.routes.internal.send_verification_code import send_otp_blueprint
from app.server.routes.internal.shorten_url import shorten_url_blueprint
from app.server.routes.your_short_url import your_short_url_blueprint
from app.server.routes.total_clicks import total_clicks_blueprint
from app.server.routes.error import error_blueprint
from app.server.routes.page_not_found import page_not_found_blueprint
from app.server.routes.api_doc import api_doc_blueprint
from app.server.routes.get_token import get_token_blueprint
from app.server.routes.your_api_token import your_api_token_blueprint
from app.server.routes.verify_code import verify_code_blueprint

from app.server.api.api import Shorten, TotalClicks, GetToken

def create_app(config_file):
    app_path = os.path.dirname(os.path.abspath(__file__))
    project_folder = os.path.expanduser(app_path)
    load_dotenv(os.path.join(project_folder, '.env'))

    app = Flask(__name__, template_folder='../client/templates', static_folder='../client/static')
    api = Api(app)


    with app.app_context():

        app_auth_token = app.secret_key
        auth_token = AuthToken(auth_token=app_auth_token)

        api.add_resource(Shorten, '/api/shorten')
        api.add_resource(GetToken, '/api/get_token')
        api.add_resource(TotalClicks, '/api/total_clicks')


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

Example 22 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 / init.py

# __init__.py
import boto3
from celery import Celery
from datetime import datetime
import os
import requests
import yaml

from flask import Flask, render_template
from flask import session as current_session
from flask_mail import Mail
from flask_migrate import Migrate, MigrateCommand
from flask.sessions import SessionInterface
from flask_sqlalchemy import SQLAlchemy
from flask_user import user_logged_out
from flask_wtf.csrf import CSRFProtect

from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from beaker.middleware import SessionMiddleware

db = SQLAlchemy()
csrf_protect = CSRFProtect()
mail = Mail()
migrate = Migrate()

def get_config():
    app = Flask(__name__)

    if 'APPLICATION_SETTINGS' in os.environ:
    if 'AWS_SECRETS_MANAGER_CONFIG' in os.environ:
        secret_config = get_secrets(os.environ['AWS_SECRETS_MANAGER_CONFIG'])
    elif 'AWS_SECRETS_MANAGER_CONFIG' in app.config:
        secret_config = get_secrets(app.config['AWS_SECRETS_MANAGER_CONFIG'])
    for setting in app.config:
        if setting in os.environ:
            if os.environ[setting].lower() == 'true':
                app.config[setting] = True
            elif os.environ[setting].lower() == 'false':
                app.config[setting] = False
                app.config[setting] = os.environ[setting]
    if app.config.get('USER_LDAP', False):
        app.config['USER_ENABLE_USERNAME'] = True
    return app.config

def get_secrets(secret_name, region=False):

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

    return yaml.safe_load(secret)

def get_secret_region():
    if 'AWS_SECRETS_REGION' in os.environ:
        return os.environ['AWS_SECRETS_REGION']

    boto3_session = boto3.session.Session()
    if boto3_session.region_name:
        return boto3_session.region_name

    r = requests.get('', timeout=0.2)
    data = r.json()
    return data['region']

base_config = get_config()

celery = Celery(__name__, broker=base_config['CELERY_BROKER'])
cache = None # Initiate below, but define here for scope reasons.

def create_app(extra_config_settings={}):
    app = Flask(__name__)

    base_config = get_config()


    migrate.init_app(app, db)



    cache = init_cache_manager(app)




    from app.extensions.jinja import jinja_extensions_blueprint

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

Example 23 from trape

trape is a research tool for tracking people's activities that are logged digitally. The tool uses Flask to create a web front end to view aggregated data on an individual the application is set to track. The source code is provided as open source under the MIT license, according to the README.

trape / core / user.py

# user.py
import time
from core.dependence import urllib2
from flask import Flask, render_template, session, request, json, Response
from core.user_objects import *
import core.stats
from core.utils import utils
from core.db import Database
import os
import sys
import platform
import urllib
import requests
from multiprocessing import Process

trape = core.stats.trape
app = core.stats.app

db = Database()

class victim_server(object):
    @app.route("/" + trape.victim_path)
    def homeVictim():
        r = requests.get(trape.url_to_clone, headers=victim_headers2(request.user_agent))
        if (trape.type_lure == 'local'):
            html = assignScripts(victim_inject_code(render_template("/" + trape.url_to_clone), 'payload', '/', trape.gmaps, trape.ipinfo))
            html = assignScripts(victim_inject_code(r.content, 'payload', trape.url_to_clone, trape.gmaps, trape.ipinfo))

## ... source file continues with no further Flask 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