Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of registering Flask Blueprints

I ran into a strange issue (maybe not so strange for experienced in flask).

I have a flask application running in the context of Google App Engine's dev_appserver.py

I have a blueprint in my flask application

# rest_server.py

rest_api = Blueprint('rest_api', __name__)
app = Flask(__name__)
app.register_blueprint(rest_api, url_prefix='/api')  # [1] DOESN'T WORK

@rest_api.route("/")
def hello():
  return "Hello World"

app.register_blueprint(rest_api, url_prefix="/api")  # [2] WORKS AS EXPECTED

I have the following in my app.yaml

-url: "/api/.*"
 script: rest_server.app

When I hit localhost:8080/api/ when I register blueprint at position [1], I get an error saying there is no matching endpoint.

However, when I register bluerpint at [2], any position after the decorator, it works.

Is it required to register the blueprint after all the decorators?

like image 940
user462455 Avatar asked Nov 21 '16 22:11

user462455


1 Answers

Yes, it's required to register blueprints only after all their routes have been declared, at least if you want to use those routes. (If you don't mind the routes not being available, it doesn't look like there's actually any problem with declaring new routes after registering the blueprint.)

If you want to know why: basically, blueprint url rules are only registered on the application when Flask.register_blueprint is called. If you add routes after registering the blueprint, they just get added to the list of things to do when the blueprint is registered (Blueprint.deferred_functions), they don't get retroactively added to any existing applications that the blueprint was registered to in the past.

like image 142
ash Avatar answered Sep 17 '22 14:09

ash