Last Updated: February 25, 2016
·
3.718K
· aschreyer

Adding custom URL map converters to Flask Blueprint objects

Blueprints in Flask are useful to divide large applications into smaller components that could be also be used in other applications such as an admin panel, for example. Blueprints implement the most important application methods that are necessary to create a fully functional app, like apperrorhandler</code> to deal with application error or addapptemplatefilter</code> to register new functions that can be used in the blueprint's themes. What is missing however is support for custom URL map converters that might be used in the URL routes of the blueprint's views. I assume it is possible to only register them in the main Flask application, however I think it is better and more consistent with the other methods to associate them directly with the blueprint. The following snippet contains a simple variation of the addapptemplate_filter</code> method to record the registration of a new converter in the main application:

from flask import Blueprint
import converters # module containing the custom converter classes

def add_app_url_map_converter(self, func, name=None):
    """
    Register a custom URL map converters, available application wide.

    :param name: the optional name of the filter, otherwise the function name
                 will be used.
    """
    def register_converter(state):
        state.app.url_map.converters[name or func.__name__] = func

    self.record_once(register_converter)

# monkey-patch the Blueprint object to allow addition of URL map converters
Blueprint.add_app_url_map_converter = add_app_url_map_converter

# create the eyesopen Flask blueprint
bp = Blueprint('myblueprint', __name__)

# register the URL map converters that are required
bp.add_app_url_map_converter(converters.FooConverter, 'foo')
bp.add_app_url_map_converter(converters.BarConverter, 'bar')

1 Response
Add your response

Thanks, that realy helped me!

over 1 year ago ·