As I started learning Flask, I was building simple apps just to understand the basics and get comfortable with it. Once I felt a bit more confident, I decided to start a project, a site monitoring tool. Since I knew the project would grow and include more functionality, I realized that things should be organized better. That’s when I came across Flask Blueprints. A Blueprint is a modular way to organize code and routes into separate components. Today, I set up my first Blueprint in Flask and here’s how it went.
Project structure
blueprint-example/
├── run.py
└── app/
└── routes.py
└── __init__.py
└── templates/
└── index.html
Step 1: Creating a simple Blueprint
from flask import Blueprint,render_template
#creating a flask blueprint called 'main_route'
main_route=Blueprint('main_route',__name__)
#define a route on this blueprint
@main_route.route('/')
def blue_example():
return render_template('index.html')
Step 2: Register the blueprint
from flask import Flask
app=Flask(__name__)
def blue_example():
from .routes import main_route
app.register_blueprint(main_route)#registering my blueprint to my flask app instance
return app
Step 3: Run the app
from app import blue_example
app=blue_example()#Calling a function to get flask app instance
if __name__ == '__main__':
app.run(debug=True) #run the app in debug mode
What i found use full?
I basically had an idea of how this works because I had learned about MVC (Model, View, and Controller) in Java. The working process of both is quite similar, so I was able to grasp it a bit quicker.
Here are a few things I found helpful about using Blueprints:
It's a clean way to split the code logically. For example, separating routes and the dashboard into components makes the structure much easier to work with.
It's much easier to manage as the app grows and more features are added.
It makes the project more organized and scalable, which is especially useful when working in teams or revisiting the project later.
Top comments (0)