Adicionando conversores de mapa de URL personalizados a objetos Flask Blueprint

Blueprints no Flask são úteis para dividir aplicativos grandes em componentes menores que também podem ser usados ​​em outros aplicativos, como um painel de administração, por exemplo. Os blueprints implementam os métodos de aplicativo mais importantes que são necessários para criar um aplicativo totalmente funcional, comoapperrorhandler</code> to deal with application error or addapptemplatefilter</code> to register new functions that canbe 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')