Overwrite route in flask blueprint
There are 2 solutions which I found. First:
from flask import Flask, Blueprintsimple_page = Blueprint('simple_page', __name__, )@simple_page.route('/my/route/')def my(): # for example it's a registered route somewhere... return 'default'@simple_page.route('/my/route/')def new_my(): # new endpoint / should works instead my() return 'new'# map of views which we won't register in Flask app# you can store this somewhere in settingsSKIP_VIEWS = ( # route, view function ('/my/route/', my, ),)class CustomFlask(Flask): def add_url_rule(self, rule, endpoint=None, view_func=None, **options): # Flask registers views when an application starts # do not add view from SKIP_VIEWS for rule_, view_func_ in SKIP_VIEWS: # type: str, func if rule_ == rule and view_func == view_func_: return return super(CustomFlask, self).add_url_rule(rule, endpoint, view_func, **options)app = CustomFlask(__name__)app.register_blueprint(simple_page)app.run(debug=True)
Second way:
two.py - default blueprint with endpoint
from flask import Blueprintbp_two = Blueprint('simple_page2', __name__, )@bp_two.route('/my/route/')def default(): return 'default'
test.py - your blueprint + app
from flask import Flask, Blueprintfrom two import bp_twoyour_bp = Blueprint('simple_page', __name__, )@your_bp.route('/my/route/')def new_route(): return 'new'app = Flask(__name__)# register blueprint and turn off '/my/route/' endpointapp.register_blueprint(bp_two, **{'url_defaults': {'/my/route/': None}})app.register_blueprint(your_bp)app.run(debug=True)
Run app. Open /my/route/
. You will see that default endpoint wasn't add/works.
Hope this helps.