0
0
FlaskHow-ToBeginner · 3 min read

How to Register Blueprint in Flask: Simple Guide

In Flask, you register a blueprint using the app.register_blueprint() method, passing the blueprint instance as an argument. This connects the blueprint's routes and views to your main Flask application.
📐

Syntax

The basic syntax to register a blueprint in Flask is:

  • app: Your main Flask application instance.
  • blueprint: The blueprint object you want to register.

Use app.register_blueprint(blueprint, url_prefix='/prefix') to add the blueprint's routes to your app with an optional URL prefix.

python
app.register_blueprint(blueprint, url_prefix='/prefix')
💻

Example

This example shows how to create a blueprint and register it with the main Flask app. The blueprint has one route that returns a greeting.

python
from flask import Flask, Blueprint

# Create the blueprint
simple_page = Blueprint('simple_page', __name__)

@simple_page.route('/hello')
def hello():
    return 'Hello from blueprint!'

# Create the main app
app = Flask(__name__)

# Register the blueprint with a URL prefix
app.register_blueprint(simple_page, url_prefix='/simple')

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

Common Pitfalls

  • Forgetting to register the blueprint with app.register_blueprint() means routes won't be available.
  • Not using a unique name for the blueprint can cause conflicts.
  • Missing the url_prefix can lead to route collisions or unexpected URLs.
  • Registering the blueprint after the app has started serving requests will not work properly.
python
from flask import Flask, Blueprint

# Wrong: Blueprint created but not registered
bp = Blueprint('bp', __name__)

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

app = Flask(__name__)

# Missing: app.register_blueprint(bp)

# Correct way:
# app.register_blueprint(bp, url_prefix='/bp')
📊

Quick Reference

Remember these tips when registering blueprints:

  • Always create the blueprint with a unique name.
  • Register the blueprint before running the app.
  • Use url_prefix to organize routes under a common path.
  • Blueprints help keep your app modular and organized.

Key Takeaways

Use app.register_blueprint() to connect blueprints to your Flask app.
Always register blueprints before starting the app to ensure routes work.
Use url_prefix to group blueprint routes under a path.
Blueprints help organize your app into reusable components.
Give each blueprint a unique name to avoid conflicts.