Passed
Push — master ( e393e9...5ba3e6 )
by Chris
01:12
created

config_flask_globals()   A

Complexity

Conditions 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 5
rs 9.4285
1
"""Provides configuration utilities for using the filters."""
2
3
from __future__ import absolute_import
4
from inspect import getmembers, isfunction
5
from . import filters, random
6
7
8
def _get_funcs(module):
9
    """Extract all functions from a module.
10
11
    Args:
12
        module (module): A python module reference.
13
14
    Returns:
15
        funcs (dict): A dictionary of names and functions extracted.
16
17
    """
18
    return {name: func for name, func
19
            in getmembers(module) if isfunction(func)}
20
21
22
def _inject_filters(app, filters):
23
    """Inject a set of filters into a Flask app.
24
25
    Args:
26
        app (object): The Flask application.
27
        filters (dict): A dictionary of name and functions.
28
29
    Returns:
30
        app (object): The Flask application.
31
    """
32
    for name, func in filters.iteritems():
33
        app.jinja_env.filters[name] = func
34
    return app
35
36
37
def config_flask_filters(app):
38
    """Register a Flask app with all the available filters.
39
40
    Args:
41
        app (object): The Flask application instance.
42
        filters (list): The list of filter functions to use.
43
44
    Returns:
45
        app (object): The modified Flask application instance.
46
    """
47
    # Manually register all module functions that were imported.
48
    app = _inject_filters(app, _get_funcs(filters))
49
    app = _inject_filters(app, _get_funcs(random))
50
    return app
51
52
53
def _inject_template_globals(app, funcs):
54
    """Inject a set of functions into a Flask app as template_globals.
55
56
    Args:
57
        app (object): The Flask application.
58
        funcs (dict): A dictionary of name and functions.
59
60
    Returns:
61
        app (object): The Flask application.
62
    """
63
    for name, func in funcs.iteritems():
64
        app.add_template_global(name, func)
65
    return app
66
67
68
def config_flask_globals(app):
69
    """Configure a Flask app to use all functions as template_globals."""
70
    app = _inject_template_globals(app, _get_funcs(filters))
71
    app = _inject_template_globals(app, _get_funcs(filters))
72
    return app
73