Flask register all template filters in one module

During my tests with Flask, the python web framework, I stumbled upon the challenge to register all my filters I had stored in app/util/filters.py.

My solution is the def init_app(app) function:

def filter_upper(text):
    return text.upper()
def filter_lower(text):
    return text.lower()
def init_app(app):
    for func in globals():
        if func.startswith('filter_'):
            name = func.split('_')[-1]
            app.add_template_filter(globals()[func], name)

The init_app function will search through all global members of the module for function definitions where the name starts with filter_. These functions are than registered to the flask app. The name of the filter is automatically generated from the function name.


Enter your comment. Wiki syntax is allowed:


Use the following URL for manually sending trackbacks: https://wiki.goatpr0n.de/lib/plugins/linkback/exe/trackback.php/blog:flask_register_all_template_filters_in_one_module
Last modified: le 2018/12/17 13:49