Blueprints
At the moment, our application has a single route defined in the run.py
file. We could
continue to add routes there, but before long it would become unwieldy. Blueprints provide
a way to structure the code so that it is easier to navigate and manage by grouping related
files together. A blueprint is registered with the application in the factory function.
Our application will eventually have four blueprints for
- Publicly accessible routes such as the home page
- Authentication functions
- Admin functions
- Staff functions
In this section we introduce the public
blueprint. This is simply a restructuring exercise -
there will be no changes to the application's behaviour. We will also add the directories
needed for the other blueprints, but we will populate them in later parts of the tutorial.
Create the blueprint directories
Each blueprint requires a directory of its own under the app
directory with a common
internal structure as shown in below.
└── students_app ├── app/ │ ├── admin/ │ │ ├── __init__.py │ │ ├── forms/ │ │ └── views/ │ ├── auth/ │ │ ├── __init__.py │ │ ├── forms/ │ │ └── views/ │ ├── public/ │ │ ├── __init__.py │ │ ├── forms/ │ │ └── views/ │ ├── staff/ │ │ ├── __init__.py │ │ ├── forms/ │ │ └── views/ │ └── templates/ └── instance/
The
forms
directory is for form layout definitions. In the case of thepublic
blueprint, that might include a Contact us form for example that should be accessible to non-authenticated users.The
views
directory will contain the definitions of endpoint functions.The
__init__.py
file contains import statements and other structural code that links the various components together.
Connect the blueprint to the application
With the structure in place, we need to add the 'wiring' that allows Flask to find the right
files when needed. Start by pasting the following code into the app/public/__init__.py
file.
1 2 3 4 5 |
|
Next, modify the factory function in app/__init__.py
file as shown below. The new lines 6
and 7 link the new blueprint to the application.
1 2 3 4 5 6 7 8 9 |
|
Relocate the existing route
Now that the restructuring is complete, we can remove the existing route from the run.py
file and put it into a file in the app/public/views
directory. We will call the file
index.py
to show that it is the main landing page for the application. At the same time,
we will replace the Hello World! message with something more appropriate.
First, remove the old route from run.py
so that the file matches the code shown below.
Notice that the route has been removed and so has the statement that imports the
render_template
function.
1 2 3 4 5 6 7 8 9 |
|
Next, create the new file app/public/views/index.py
and paste in the following code.
1 2 3 4 5 6 7 8 9 |
|
Test run
Restart the application, and you should see the Hello World! message replaced with Student Management. Not much of a payoff for so much work, but the improved structure will make a lot of difference later on.