Flask Unchained API

flask_unchained.app_factory

AppFactory

The Application Factory Pattern for Flask Unchained.

flask_unchained.app_factory_hook

AppFactoryHook

Base class for hooks.

flask_unchained.bundles

AppBundle

Like Bundle, except used for the top-most application bundle.

Bundle

Base class for bundles.

flask_unchained.config

BundleConfig

Base class for configuration settings.

flask_unchained.di

Service

Base class for services.

flask_unchained.flask_unchained

FlaskUnchained

A simple subclass of flask.Flask.

flask_unchained.forms

FlaskForm

Base form class extending flask_wtf.FlaskForm.

flask_unchained.hooks

ConfigureAppHook

Updates app.config with the settings from each bundle.

InitExtensionsHook

Initializes extensions found in bundles with the current app.

RegisterCommandsHook

Registers commands and command groups from bundles.

RegisterExtensionsHook

Registers extensions found in bundles with the unchained extension.

RegisterServicesHook

Registers services for dependency injection.

RunHooksHook

An internal hook to discover and run all the other hooks.

ViewsHook

Allows configuring bundle views modules.

flask_unchained.string_utils

right_replace(string, old, new[, count])

Right replaces count occurrences of old with new in string.

slugify(string)

Converts a string into a url-safe slug.

pluralize(word[, pos, custom, classical])

Returns the plural of a given word, e.g., child => children.

singularize(word[, pos, custom])

Returns the singular of a given word.

camel_case(string)

Converts a string to camel case.

class_case(string)

Converts a string to class case.

kebab_case(string)

Converts a string to kebab case.

snake_case(string)

Converts a string to snake case.

title_case(string)

Converts a string to title case.

flask_unchained.unchained

Unchained

The Unchained extension.

flask_unchained.utils

AttrDict

A dictionary that allows using the dot operator to get and set keys.

ConfigProperty

Allows extension classes to create properties that proxy to the config value, eg app.config[key].

ConfigPropertyMetaclass

Use this metaclass to enable config properties on extension classes.

cwd_import(module_name)

Attempt to import a module from the current working directory.

get_boolean_env(name, default)

Converts environment variables to boolean values.

safe_import_module(module_name)

Like importlib.import_module(), except it does not raise ImportError if the requested module_name is not found.

utcnow()

Returns a current timezone-aware datetime.datetime in UTC.

Constants

DEV

flask_unchained.constants.DEV

Used to specify the development environment.

PROD

flask_unchained.constants.PROD

Used to specify the production environment.

STAGING

flask_unchained.constants.STAGING

Used to specify the staging environment.

TEST

flask_unchained.constants.TEST

Used to specify the test environment.

injectable

flask_unchained.di.injectable = 'INJECTABLE_PARAMETER'

Use this to mark a service parameter as injectable. For example:

class MyService(Service):
    a_dependency: ADependency = injectable

This allows MyService to be used in two ways:

# 1. using dependency injection with Flask Unchained
my_service = MyService()

# 2. overriding the dependency injection (or used without Flask Unchained)
a_dependency = ADependency()
my_service = MyService(a_dependency)

# but, if you try to use it without Flask Unchained and without parameters:
my_service = MyService()  # raises ServiceUsageError

AppFactory

class flask_unchained.AppFactory[source]

The Application Factory Pattern for Flask Unchained.

APP_CLASS

alias of flask_unchained.flask_unchained.FlaskUnchained

create_app(env: Union[development, production, staging, test], bundles: Optional[List[str]] = None, *, _config_overrides: Optional[Dict[str, Any]] = None, _load_unchained_config: bool = True, **app_kwargs) → flask_unchained.flask_unchained.FlaskUnchained[source]

Flask Unchained Application Factory. Returns an instance of APP_CLASS (by default, FlaskUnchained).

Example Usage:

app = AppFactory().create_app(PROD)
Parameters
  • env (str) – Which environment the app should run in. Should be one of “development”, “production”, “staging”, or “test” (you can import them: from flask_unchained import DEV, PROD, STAGING, TEST)

  • bundles (List[str]) – An optional list of bundle modules names to use. Overrides unchained_config.BUNDLES (mainly useful for testing).

  • app_kwargs (Dict[str, Any]) – keyword argument overrides for the APP_CLASS constructor

  • _config_overrides – a dictionary of config option overrides; meant for test fixtures (for internal use only).

  • _load_unchained_config – Whether or not to try to load unchained_config (for internal use only).

Returns

The initialized APP_CLASS app instance, ready to rock’n’roll

static load_unchained_config(env: Union[development, production, staging, test]) → module[source]

Load the unchained config from the current working directory for the given environment. If env == "test", look for tests._unchained_config, otherwise check the value of the UNCHAINED environment variable, falling back to loading the unchained_config module.

get_app_kwargs(app_kwargs: Dict[str, Any], bundles: List[flask_unchained.bundles.Bundle], env: Union[development, production, staging, test], unchained_config: Dict[str, Any]) → Dict[str, Any][source]

Returns app_kwargs with default settings applied from unchained_config.

classmethod load_bundles(bundle_package_names: Optional[List[str]] = None, unchained_config_module: Optional[module] = None) → Tuple[Union[None, flask_unchained.bundles.AppBundle], List[flask_unchained.bundles.Bundle]][source]

Load bundle instances from the given list of bundle packages. If unchained_config_module is given and there was no app bundle listed in bundle_package_names, attempt to load the app bundle from the unchained config.

classmethod load_bundle(bundle_package_name: str) → Union[flask_unchained.bundles.AppBundle, flask_unchained.bundles.Bundle][source]

Attempt to load the bundle instance from the given package.

classmethod bundle_from_module(module: module) → Union[flask_unchained.bundles.AppBundle, flask_unchained.bundles.Bundle, None][source]

Attempt to instantiate the bundle class from the given module.

AppFactoryHook

class flask_unchained.AppFactoryHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Base class for hooks.

Hooks have one entry point, run_hook(), which can be overridden to completely customize the behavior of the subclass. The default behavior is to look for objects in bundle_module_names which pass the result of type_check(). These objects are collected from all bundles into a dictionary with keys the result of key_name(), starting from the base-most bundle, allowing bundle subclasses to override objects with the same name from earlier bundles.

Subclasses should implement at a minimum bundle_module_names, process_objects(), and type_check(). You may also need to set one or both of run_before or run_after. Also of interest, hooks can store objects on their bundle’s instance, using bundle. Hooks can also modify the shell context using update_shell_context().

name: str = 'app_factory_hook'

The name of this hook. Defaults to the snake_cased class name.

run_before: Union[List[str], Tuple[str, ...]] = ()

An optional list of hook names that this hook must run before.

run_after: Union[List[str], Tuple[str, ...]] = ()

An optional list of hook names that this hook must run after.

bundle_module_name: Optional[str] = None

If require_exactly_one_bundle_module is True, only load from this module name in bundles. Should be set to None if your hook does not use that default functionality.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = None

A list of the default module names this hook will load from in bundles. Should be set to None if your hook does not use that default functionality (or require_exactly_one_bundle_module is True).

require_exactly_one_bundle_module: bool = False

Whether or not to require that there must be exactly one module name to load from in bundles.

bundle_override_module_names_attr: str = None

The attribute name that bundles can set on themselves to override the module(s) this hook will load from for that bundle. The defaults are as follows:

If require_exactly_one_bundle_module and bundle_module_name are set, use f'{YourHook.bundle_module_name}_module_name'.

Otherwise if bundle_module_names is set, we use the same f-string, just with the first module name listed in bundle_module_names.

If neither of bundle_module_name or bundle_module_names is set, then this will be None.

discover_from_bundle_superclasses: bool = True

Whether or not to search the whole bundle hierarchy for objects.

limit_discovery_to_local_declarations: bool = True

Whether or not to only include objects declared within bundles (ie not imported from other places, like third-party code).

unchained = None

The Unchained extension instance.

bundle = None

The Bundle instance this hook is from (if any).

run_hook(app: flask_unchained.flask_unchained.FlaskUnchained, bundles: List[flask_unchained.bundles.Bundle], unchained_config: Optional[Dict[str, Any]] = None) → None[source]

Hook entry point. Override to disable standard behavior of iterating over bundles to discover objects and processing them.

process_objects(app: flask_unchained.flask_unchained.FlaskUnchained, objects: Dict[str, Any]) → None[source]

Implement to do stuff with discovered objects (eg, registering them with the app instance).

collect_from_bundles(bundles: List[flask_unchained.bundles.Bundle], *, _initial_objects: Optional[Dict[str, Any]] = None) → Dict[str, Any][source]

Collect objects where type_check() returns True from bundles. Discovered names (keys, typically the class names) are expected to be unique across bundle hierarchies, except for the app bundle, which can override anything from other bundles.

collect_from_bundle(bundle: flask_unchained.bundles.Bundle) → Dict[str, Any][source]

Collect objects where type_check() returns True from bundles. Bundle subclasses can override objects discovered in superclass bundles.

key_name(name: str, obj: Any) → str[source]

Override to use a custom key to determine uniqueness/overriding.

type_check(obj: Any) → bool[source]

Implement to determine which objects in a module should be processed by this hook.

classmethod import_bundle_modules(bundle: flask_unchained.bundles.Bundle) → List[module][source]

Safe-import the modules in a bundle for this hook to load from.

classmethod get_module_names(bundle: flask_unchained.bundles.Bundle) → List[str][source]

The list of fully-qualified module names for a bundle this hook should load from.

classmethod get_bundle_module_names(bundle: flask_unchained.bundles.Bundle) → List[str][source]

The list of module names inside a bundle this hook should load from.

update_shell_context(ctx: Dict[str, Any]) → None[source]

Implement to add objects to the CLI shell context.

AppBundle

class flask_unchained.AppBundle[source]

Like Bundle, except used for the top-most application bundle.

name: str = 'app'

Name of the bundle. Defaults to the snake_cased class name, excluding any “Bundle” suffix.

Bundle

class flask_unchained.Bundle[source]

Base class for bundles.

Should be placed in your package’s root or its bundle module:

# your_bundle_package/__init__.py or your_bundle_package/bundle.py

class YourBundle(Bundle):
    pass
name: str = 'bundle'

Name of the bundle. Defaults to the snake_cased class name.

module_name: str = 'flask_unchained.bundles'

Top-level module name of the bundle (dot notation).

Automatically determined; read-only.

root_path: str = '/home/docs/checkouts/readthedocs.org/user_builds/flask-unchained/envs/latest/lib/python3.7/site-packages/Flask_Unchained-0.9.0-py3.7.egg/flask_unchained/bundles'

Root directory path of the bundle’s package.

Automatically determined; read-only.

template_folder

Root directory path of the bundle’s template folder. By default, if there exists a folder named templates in the bundle package root_path, it will be used, otherwise None.

static_folder

Root directory path of the bundle’s static assets folder. By default, if there exists a folder named static in the bundle package root_path, it will be used, otherwise None.

static_url_path

Url path where this bundle’s static assets will be served from. If static_folder is set, this will default to /<bundle.name>/static, otherwise None.

is_single_module: bool = False

Whether or not the bundle is a single module (Python file).

Automatically determined; read-only.

default_load_from_module_name: Optional[str] = None

The default module name for hooks to load from. Set hooks’ bundle modules override attributes for the modules you want in separate files.

WARNING - EXPERIMENTAL

Using this feature may cause mysterious exceptions to be thrown!!

Best practice is to organize your code in separate modules.

before_init_app(app: flask_unchained.flask_unchained.FlaskUnchained) → None[source]

Override this method to perform actions on the FlaskUnchained app instance before the unchained extension has initialized the application.

after_init_app(app: flask_unchained.flask_unchained.FlaskUnchained) → None[source]

Override this method to perform actions on the FlaskUnchained app instance after the unchained extension has initialized the application.

BundleConfig

class flask_unchained.BundleConfig[source]

Base class for configuration settings. Allows access to the app-under-construction as it’s currently configured. Example usage:

# your_bundle_root/config.py

import os

from flask_unchained import BundleConfig

class Config(BundleConfig):
    SHOULD_PRETTY_PRINT_JSON = BundleConfig.current_app.config.DEBUG

FlaskUnchained

class flask_unchained.FlaskUnchained(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[str] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', instance_path: Optional[str] = None, instance_relative_config: bool = False, root_path: Optional[str] = None)[source]

A simple subclass of flask.Flask. Overrides register_blueprint() and add_url_rule() to support automatic (optional) registration of URLs prefixed with a language code.

config_class

alias of AttrDictFlaskConfig

env: str = None

The environment the application is running in. Will be one of development, production, staging, or test.

unchained

The Unchained extension instance.

register_blueprint(blueprint: flask.blueprints.Blueprint, *, register_with_babel: bool = True, **options: Any) → None[source]

The same as flask.Flask.register_blueprint(), but if register_with_babel is True, then we also allow the Babel Bundle an opportunity to register language code prefixed URLs.

add_url_rule(rule: str, endpoint: Optional[str] = None, view_func: Optional[function] = None, provide_automatic_options: Optional[bool] = None, *, register_with_babel: bool = False, **options: Any) → None[source]

The same as flask.Flask.add_url_rule(), but if register_with_babel is True, then we also allow the Babel Bundle an opportunity to register a language code prefixed URL.

Service

class flask_unchained.Service[source]

Base class for services. Automatically sets up dependency injection on the constructor of the subclass, and allows for your service to be automatically detected and used.

Hooks

ConfigureAppHook

class flask_unchained.hooks.ConfigureAppHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Updates app.config with the settings from each bundle.

name: str = 'configure_app'

The name of this hook.

bundle_module_name: Optional[str] = 'config'

The default module this hook loads from.

Override by setting the config_module_name attribute on your bundle class.

run_hook(app: flask_unchained.flask_unchained.FlaskUnchained, bundles: List[flask_unchained.bundles.Bundle], unchained_config: Optional[Dict[str, Any]] = None) → None[source]

For each bundle in unchained_config.BUNDLES, iterate through that bundle’s class hierarchy, starting from the base-most bundle. For each bundle in that order, look for a config module, and if it exists, update app.config with the options first from a base Config class, if it exists, and then also if it exists, from an env-specific config class: one of DevConfig, ProdConfig, StagingConfig, or TestConfig.

get_bundle_config(bundle: flask_unchained.bundles.Bundle, env: Union[development, production, staging, test]) → flask.config.Config[source]

Get the config settings from a bundle hierarchy.

InitExtensionsHook

class flask_unchained.hooks.InitExtensionsHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Initializes extensions found in bundles with the current app.

name: str = 'init_extensions'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['extensions']

The default module this hook loads from.

Override by setting the extensions_module_names attribute on your bundle class.

process_objects(app: flask_unchained.flask_unchained.FlaskUnchained, extensions: Dict[str, object]) → None[source]

Initialize each extension with extension.init_app(app).

update_shell_context(ctx: Dict[str, Any]) → None[source]

Add extensions to the CLI shell context.

RegisterCommandsHook

class flask_unchained.hooks.RegisterCommandsHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Registers commands and command groups from bundles.

name: str = 'commands'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['commands']

The default module this hook loads from.

Override by setting the commands_module_names attribute on your bundle class.

run_hook(app: flask_unchained.flask_unchained.FlaskUnchained, bundles: List[flask_unchained.bundles.Bundle], unchained_config: Optional[Dict[str, Any]] = None) → Dict[str, Union[click.core.Command, click.core.Group]][source]

Discover CLI commands and command groups from bundles and register them with the app.

RegisterExtensionsHook

class flask_unchained.hooks.RegisterExtensionsHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Registers extensions found in bundles with the unchained extension.

name: str = 'register_extensions'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['extensions']

The default module this hook loads from.

Override by setting the extensions_module_names attribute on your bundle class.

process_objects(app: flask_unchained.flask_unchained.FlaskUnchained, extensions: Dict[str, object]) → None[source]

Discover extensions in bundles and register them with the Unchained extension.

collect_from_bundle(bundle: flask_unchained.bundles.Bundle) → Dict[str, object][source]

Collect declared extensions from a bundle hierarchy.

RegisterServicesHook

class flask_unchained.hooks.RegisterServicesHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Registers services for dependency injection.

name: str = 'services'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['services', 'managers']

The default modules this hook loads from.

Override by setting the services_module_names attribute on your bundle class.

process_objects(app: flask_unchained.flask_unchained.FlaskUnchained, services: Dict[str, flask_unchained.di.Service]) → None[source]

Register services with the Unchained extension, initialize them, and inject any requested into extensions.

key_name(name, obj) → str[source]

Returns the service’s dependency injection name.

type_check(obj) → bool[source]

Returns True if obj is a concrete subclass of Service.

update_shell_context(ctx: Dict[str, Any]) → None[source]

Add services to the CLI shell context.

RunHooksHook

class flask_unchained.hooks.RunHooksHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

An internal hook to discover and run all the other hooks.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['hooks']

The default module this hook loads from.

Override by setting the hooks_module_names attribute on your bundle class.

run_hook(app: flask_unchained.flask_unchained.FlaskUnchained, bundles: List[flask_unchained.bundles.Bundle], unchained_config: Optional[Dict[str, Any]] = None) → None[source]

Collect hooks from Flask Unchained and the list of bundles, resolve their correct order, and run them in that order to build (boot) the app instance.

collect_from_bundle(bundle: flask_unchained.bundles.Bundle) → Dict[str, flask_unchained.hooks.run_hooks_hook.HookTuple][source]

Collect hooks from a bundle hierarchy.

collect_unchained_hooks() → Dict[str, flask_unchained.hooks.run_hooks_hook.HookTuple][source]

Collect hooks built into Flask Unchained that should always run.

type_check(obj: Any) → bool[source]

Returns True if obj is a subclass of AppFactoryHook.

ViewsHook

class flask_unchained.hooks.ViewsHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Allows configuring bundle views modules.

name: str = 'views'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['views']

The default module this hook loads from.

Override by setting the views_module_names attribute on your bundle class.

run_hook(app, bundles, unchained_config=None) → None[source]

Hook entry point. Override to disable standard behavior of iterating over bundles to discover objects and processing them.

Unchained

class flask_unchained.Unchained(env: Union[development, production, staging, test, None] = None)[source]

The Unchained extension. Responsible for initializing the app by loading all the things from bundles, keeping references to all of the various discovered bundles and things inside them, and for doing dependency injection. To get access to the unchained extension instance:

from flask_unchained import unchained

Also acts as a replacement for some of the public API of flask.Flask. (The part that allows registering url rules, functions to run for handling errors, functions to run during the normal request response cycle, and methods for setting up the Jinja templating environment.)

get_local_proxy(name)[source]

Returns a LocalProxy to the extension or service with name as registered with the current app.

service(name: str = None)[source]

Decorator to mark something as a service.

register_service(name: str, service: Any)[source]

Method to register a service.

inject(*args)[source]

Decorator to mark a class, method, or function as needing dependencies injected.

Example usage:

from flask_unchained import unchained, injectable

# automatically figure out which params to inject
@unchained.inject()
def my_function(not_injected, some_service: SomeService = injectable):
    # do stuff

# or declare injectables explicitly (makes the ``injectable`` default optional)
@unchained.inject('some_service')
def my_function(not_injected, some_service: SomeService):
    # do stuff

# use it on a class to set up class attributes injection (and the constructor)
@unchained.inject()
class MyClass:
    some_service: SomeService = injectable

    def __init__(self, another_service: AnotherService = injectable):
        self.another_service = another_service
add_url_rule(rule, endpoint=None, view_func=None, **options)[source]

Register a new url rule. Acts the same as flask.Flask.add_url_rule().

before_request(fn=None)[source]

Registers a function to run before each request.

For example, this can be used to open a database connection, or to load the logged in user from the session.

The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.

before_first_request(fn=None)[source]

Registers a function to be run before the first request to this instance of the application.

The function will be called without any arguments and its return value is ignored.

after_request(fn=None)[source]

Register a function to be run after each request.

Your function must take one parameter, an instance of response_class and return a new response object or the same (see process_response()).

As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred.

teardown_request(fn=None)[source]

Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed.

Example:

ctx = app.test_request_context()
ctx.push()
...
ctx.pop()

When ctx.pop() is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.

Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors.

When a teardown function was called because of an exception it will be passed an error object.

The return values of teardown functions are ignored.

Debug Note

In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.

teardown_appcontext(fn=None)[source]

Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped.

Example:

ctx = app.app_context()
ctx.push()
...
ctx.pop()

When ctx.pop() is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.

Since a request context typically also manages an application context it would also be called when you pop a request context.

When a teardown function was called because of an unhandled exception it will be passed an error object. If an errorhandler() is registered, it will handle the exception and the teardown will not receive it.

The return values of teardown functions are ignored.

context_processor(fn=None)[source]

Registers a template context processor function.

shell_context_processor(fn=None)[source]

Registers a shell context processor function.

url_value_preprocessor(fn=None)[source]

Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions.

The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view.

The function is passed the endpoint name and values dict. The return value is ignored.

url_defaults(fn=None)[source]

Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.

errorhandler(code_or_exception)[source]

Register a function to handle errors by code or exception class.

A decorator that is used to register a function given an error code. Example:

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

You can also register handlers for arbitrary exceptions:

@app.errorhandler(DatabaseError)
def special_exception_handler(error):
    return 'Database connection failed', 500
Parameters

code_or_exception – the code as integer for the handler, or an arbitrary exception

template_filter(arg: Optional[Callable] = None, *, name: Optional[str] = None, pass_context: bool = False, inject: Union[bool, Iterable[str], None] = None, safe: bool = False) → Callable[source]

Decorator to mark a function as a Jinja template filter.

Parameters
  • name – The name of the filter, if different from the function name.

  • pass_context – Whether or not to pass the template context into the filter. If True, the first argument must be the context.

  • inject – Whether or not this filter needs any dependencies injected.

  • safe – Whether or not to mark the output of this filter as html-safe.

template_global(arg: Optional[Callable] = None, *, name: Optional[str] = None, pass_context: bool = False, inject: Union[bool, Iterable[str], None] = None, safe: bool = False) → Callable[source]

Decorator to mark a function as a Jinja template global (tag).

Parameters
  • name – The name of the tag, if different from the function name.

  • pass_context – Whether or not to pass the template context into the tag. If True, the first argument must be the context.

  • inject – Whether or not this tag needs any dependencies injected.

  • safe – Whether or not to mark the output of this tag as html-safe.

template_tag(arg: Optional[Callable] = None, *, name: Optional[str] = None, pass_context: bool = False, inject: Union[bool, Iterable[str], None] = None, safe: bool = False) → Callable[source]

Alias for template_global().

Parameters
  • name – The name of the tag, if different from the function name.

  • pass_context – Whether or not to pass the template context into the tag. If True, the first argument must be the context.

  • inject – Whether or not this tag needs any dependencies injected.

  • safe – Whether or not to mark the output of this tag as html-safe.

template_test(arg: Optional[Callable] = None, *, name: Optional[str] = None, inject: Union[bool, Iterable[str], None] = None, safe: bool = False) → Callable[source]

Decorator to mark a function as a Jinja template test.

Parameters
  • name – The name of the test, if different from the function name.

  • inject – Whether or not this test needs any dependencies injected.

  • safe – Whether or not to mark the output of this test as html-safe.

string_utils

flask_unchained.string_utils.right_replace(string, old, new, count=1)[source]

Right replaces count occurrences of old with new in string. For example:

right_replace('one_two_two', 'two', 'three') -> 'one_two_three'
flask_unchained.string_utils.slugify(string)[source]

Converts a string into a url-safe slug. For example:

slugify('Hello World') -> 'hello-world'
flask_unchained.string_utils.pluralize(word, pos='NN', custom=None, classical=True)[source]

Returns the plural of a given word, e.g., child => children. Handles nouns and adjectives, using classical inflection by default (i.e., where “matrix” pluralizes to “matrices” and not “matrixes”). The custom dictionary is for user-defined replacements.

flask_unchained.string_utils.singularize(word, pos='NN', custom=None)[source]

Returns the singular of a given word.

flask_unchained.string_utils.camel_case(string)[source]

Converts a string to camel case. For example:

camel_case('one_two_three') -> 'oneTwoThree'
flask_unchained.string_utils.class_case(string)[source]

Converts a string to class case. For example:

class_case('one_two_three') -> 'OneTwoThree'
flask_unchained.string_utils.kebab_case(string)[source]

Converts a string to kebab case. For example:

kebab_case('one_two_three') -> 'one-two-three'

NOTE: To generate valid slugs, use slugify()

flask_unchained.string_utils.snake_case(string)[source]

Converts a string to snake case. For example:

snake_case('OneTwoThree') -> 'one_two_three'
flask_unchained.string_utils.title_case(string)[source]

Converts a string to title case. For example:

title_case('one_two_three') -> 'One Two Three'

utils

class flask_unchained.utils.AttrDict[source]

A dictionary that allows using the dot operator to get and set keys.

class flask_unchained.utils.ConfigProperty(key=None)[source]

Allows extension classes to create properties that proxy to the config value, eg app.config[key].

If key is left unspecified, in will be injected by ConfigPropertyMetaclass, defaulting to f'{ext_class_name}_{property_name}'.upper().

class flask_unchained.utils.ConfigPropertyMetaclass(class_name, bases, clsdict)[source]

Use this metaclass to enable config properties on extension classes. I’m not sold on this being a good idea for new extensions, but for backwards compatibility with existing extensions that have silly __getattr__ magic, I think it’s a big improvement. (NOTE: this only works when the application context is available, but that’s no different than the behavior of what it’s meant to replace.)

Example usage:

class MyExtension(metaclass=ConfigPropertyMetaclass):
    __config_prefix__ = 'MY_EXTENSION'
    # if __config_prefix__ is unspecified, default is class_name.upper()

    foobar: Optional[FunctionType] = ConfigProperty()
    _custom: Optional[str] = ConfigProperty('MY_EXTENSION_CUSTOM')

my_extension = MyExtension(app)
my_extension.foobar == current_app.config.MY_EXTENSION_FOOBAR
my_extension._custom == current_app.config.MY_EXTENSION_CUSTOM
flask_unchained.utils.cwd_import(module_name)[source]

Attempt to import a module from the current working directory.

Raises ImportError if not found, or the found module isn’t from the current working directory.

flask_unchained.utils.get_boolean_env(name, default)[source]

Converts environment variables to boolean values. Truthy is defined as: value.lower() in {'true', 'yes', 'y', '1'} (everything else is falsy).

flask_unchained.utils.safe_import_module(module_name)[source]

Like importlib.import_module(), except it does not raise ImportError if the requested module_name is not found.

flask_unchained.utils.utcnow()[source]

Returns a current timezone-aware datetime.datetime in UTC.