Utilizing Blueprints
00:00 Blueprints provide a way to organize related functionality into reusable components. Think of them as separate building plans for different sections of a house.
00:09 They are essential for managing larger Flask applications, keeping code clean, and promoting modularity. So why do we use blueprints? Blueprints are invaluable for the ability to organize routes, templates, static files, and other resources within a self-contained module.
00:27
This modularity simplifies development and maintenance, especially as your application grows and becomes more complex. Now let’s see this in action. In your project, create a new file called pages.py
within the board
folder.
00:44
This creates a Blueprint named pages
. This blueprint object is similar to a mini-Flask application. We define our routes using @bp.route()
decorator, just like we did in our initial app.py
file.
01:00
Now, you need to tell the main Flask application about this blueprint. Back in our __init__.py
file within the create_app()
function, just add the following line.
01:13
This app.register_blueprint()
line registers our pages
blueprint with the main app. This makes the routes defined within the blueprint accessible through our main application.
01:23
Now we need to import this. Otherwise, we will see a warning that says pages
is not defined. So let’s import pages. Now, let’s go ahead and run this and see your progress.
01:38 First, like we did before, let’s activate the virtual environment
01:44 and now enter this command.
01:48
Now instead of just passing the run
command like we did before, we need to pass which app to run. We will run the board
app,
02:00
and again, you should see the address printed on your screen. Now browse to this address in your browser. You will see “Hello, Home!” as the home screen and if it type /about
, you will see “Hello, About!”
02:17
and that is what is defined in our pages.py
file. The /
should show “Hello, Home!” and /about
should show “Hello, About!”, and that is what is being shown in our app.
02:31 In this lesson, you learn how to use blueprints to modularize your flask application by organizing routes. This approach keeps your code base clean and scalable as your project grows.
02:42 In the next lesson, you will build on this by creating child templates to make your HTML more reusable and efficient.
Become a Member to join the conversation.