Here I am going to detail the two points that you mentioned. You can also read this response that details the use of blueprint and check the flask official example on github.
a blueprint defers the need for an application by recording them for later registrations
A good practice for bigger applications is to use Application Factory. There are multiple reasons to use that:
- Testing.
- Multiple instances.
Application factory looks like:
def create_app():
app = Flask(__name__)
return app
When you start your application with the following commands, flask will look for create_app function and call it:
$ export FLASK_APP=myapp
$ flask run
Now that your application is running, the app object is not accessible outside the scope of the function because it will be created while flask run is executed. So you can not do in your file:
def create_app():
...
@app.route() # this does not work, because app does not exist.
For small applications or specific cases, you could define your route inside the create_app.
def create_app():
app = Flask(__name__)
@app.route("Hello")
def hello():
return "Hello"
return app
You clearly see the problem now. You are going to create all your routes inside a unique function (unreadable, bad practices, ...)
Here comes the blueprint. If you have created blueprints in your app (see flaskr example). You can register them in create_app when flask run is executed. You can register them whenever you want in your create_app after some initialization of extensions, some startup code, or whatever. You can also do dynamic registration.
def create_app():
app = Flask(__name__)
# apply the blueprints to the app
from mymodule import auth, blog
app.register_blueprint(auth.bp)
app.register_blueprint(blog.bp)
For the second point:
a Blueprint is an object that allows defining application functions without requiring application object ahead of time.
As you can see above, when we register a blueprint to an app. The blueprint does not know the app.
app.register(blueprint) # blueprint is registered to the app.
# unlike extensions that need to know the app.
db.init_app(app) # initialization and the app is giving to the extension.
Blueprint can create routes without the app object and can be attached to an existing app. So you can define your routes as they are in an app without really being in.
They are multiple advantages to use blueprints, routes as a module, multiple blueprints, provide template filters, static files, templates, and other utilities through blueprints, ... Some are details here: Modular Applications with Blueprints
The flask documentation is really well documented and everything that I have explained are explained in the flask documentation. Also the flaskr example is the most correct way to create a basic app and there is a official tutorial for following the different steps of the creation of flaskr.