How to Fix Python Flask Blueprint Not Registering
In this tutorial, you'll learn about How to Fix Python Flask Blueprint Not Registering. We cover key concepts, practical examples, and best practices.
Flask blueprints return 404 when routes are defined but the blueprint is not registered on the app, or when the url_prefix does not match the requested URL.
The Wrong Way
# admin.py
from flask import Blueprint
admin = Blueprint('admin', __name__)
@admin.route('/dashboard')
def dashboard():
return "Admin Dashboard"
# app.py
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run()
Visiting /dashboard returns 404 Not Found.
The Right Way
# admin.py
from flask import Blueprint
admin = Blueprint('admin', __name__)
@admin.route('/dashboard')
def dashboard():
return "Admin Dashboard"
# app.py
from flask import Flask
from admin import admin
app = Flask(__name__)
app.register_blueprint(admin, url_prefix='/admin')
if __name__ == '__main__':
app.run()
Visiting /admin/dashboard returns "Admin Dashboard".
Prevention Tips
- Always call
app.register_blueprint()to activate blueprint routes. - Use
url_prefixto namespace blueprint routes. - Import the blueprint instance before registering it.
- Use
blueprint_name.url_mapto inspect registered routes. - Use
url_for('blueprint_name.endpoint')to generate URLs.
Common Mistakes with flask blueprint
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro