0
0
FlaskHow-ToBeginner · 4 min read

How to Create Blueprint in Flask: Simple Guide

In Flask, create a Blueprint by importing it from flask, defining it with a name and import name, then registering it on your main app with app.register_blueprint(). Blueprints help organize routes and views into reusable modules.
📐

Syntax

A Blueprint is created by calling Blueprint(name, import_name). Then you define routes on it like a normal Flask app. Finally, register it on the main app with app.register_blueprint(blueprint).

  • name: a string identifier for the blueprint
  • import_name: usually __name__, helps Flask locate resources
python
from flask import Blueprint

bp = Blueprint('bp_name', __name__)

@bp.route('/')
def home():
    return 'Hello from Blueprint!'

# In main app:
# app.register_blueprint(bp)
💻

Example

This example shows how to create a blueprint, define a route on it, and register it with the main Flask app. When you visit /bp/, it returns a message from the blueprint.

python
from flask import Flask, Blueprint

bp = Blueprint('bp', __name__, url_prefix='/bp')

@bp.route('/')
def bp_home():
    return 'Hello from Blueprint!'

app = Flask(__name__)
app.register_blueprint(bp)

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the app and visiting http://localhost:5000/bp/ shows: Hello from Blueprint!
⚠️

Common Pitfalls

  • Forgetting to register the blueprint on the main app means routes won’t work.
  • Not setting url_prefix can cause route conflicts.
  • Using the wrong import_name can cause resource loading errors.
  • Defining routes outside the blueprint or app context causes errors.
python
from flask import Flask, Blueprint

# Wrong: Not registering blueprint
bp = Blueprint('bp', __name__)

@bp.route('/')
def home():
    return 'Hello'

app = Flask(__name__)
# Missing: app.register_blueprint(bp)  # This causes routes to not work

# Correct way:
# app.register_blueprint(bp)
📊

Quick Reference

Blueprint Usage StepDescription
Import Blueprintfrom flask import Blueprint
Create Blueprintbp = Blueprint('name', __name__, url_prefix='/prefix')
Define Routes@bp.route('/') def func(): return 'response'
Create Flask Appapp = Flask(__name__)
Register Blueprintapp.register_blueprint(bp)
Run Appapp.run(debug=True)

Key Takeaways

Create a Blueprint with Blueprint('name', __name__, url_prefix='/prefix') to organize routes.
Define routes on the blueprint just like on the main Flask app.
Always register the blueprint on the main app using app.register_blueprint().
Use url_prefix to avoid route conflicts and group blueprint routes.
Blueprints help keep your Flask app modular and easier to maintain.