A Blueprint in Flask is a way to organize your application into smaller and reusable components. It allows you to group related routes, templates, static files, and other functionality into a cohesive module. This helps in managing large applications by keeping related code together and promoting modular design.
Example of Using Blueprints in Flask
Let's say you have an application that has an admin interface and a user interface. You can create separate blueprints for each.
Create a Blueprint for the Admin Interface
First, create a directory for your admin blueprint and add the necessary files.
Directory Structure:
/yourapp
/admin
__init__.py
routes.py
app.py
admin/init.py:
from flask import Blueprintadmin_bp =Blueprint('admin',__name__)from.import routes
admin/routes.py:
from flask import render_templatefrom.import admin_bp@admin_bp.route('/admin')defadmin_home():returnrender_template('admin_home.html')
Create a Blueprint for the User Interface
Similarly, create a directory for your user blueprint and add the necessary files.
Directory Structure:
user/init.py:
user/routes.py:
Register Blueprints in Your Main Application
Now, register the blueprints in your main application file.
app.py:
Templates
Create templates for the admin and user interfaces.
templates/admin_home.html:
templates/user_home.html:
Explanation
Blueprint Creation: We create blueprints in admin/__init__.py and user/__init__.py.
Route Definition: Routes are defined in admin/routes.py and user/routes.py.
Blueprint Registration: In app.py, we register the blueprints with specific URL prefixes (/admin and /user).
Templates: Separate templates for the admin and user interfaces.
By using blueprints, you can keep your code organized and maintainable, especially as your application grows in complexity.
from flask import Blueprint
user_bp = Blueprint('user', __name__)
from . import routes
from flask import render_template
from . import user_bp
@user_bp.route('/user')
def user_home():
return render_template('user_home.html')
from flask import Flask
from admin import admin_bp
from user import user_bp
app = Flask(__name__)
app.register_blueprint(admin_bp, url_prefix='/admin')
app.register_blueprint(user_bp, url_prefix='/user')
if __name__ == '__main__':
app.run(debug=True)
<!doctype html>
<html>
<head>
<title>Admin Home</title>
</head>
<body>
<h1>Welcome to the Admin Dashboard</h1>
</body>
</html>
<!doctype html>
<html>
<head>
<title>User Home</title>
</head>
<body>
<h1>Welcome to the User Dashboard</h1>
</body>
</html>