Welcome back to CodeYourCraft! Today, we're diving into an exciting topic: Flask Blueprints. Blueprints are a powerful tool that allows you to create complex applications by organizing your code into reusable and modular pieces. Let's get started!
In Flask, Blueprints are simply a collection of routes, templates, static files, and other blueprints, grouped together to form a self-contained application. They're like building blocks for your larger Flask application, helping you keep your code organized and manageable.
To create a blueprint, first, you need to import the Flask and url_for modules:
from flask import Flask, Blueprint, url_forNext, create a new blueprint instance, giving it a name:
my_blueprint = Blueprint('my_blueprint', __name__)In the above example, my_blueprint is the name we've given to our blueprint. The second argument __name__ refers to the current module's name.
After creating the blueprint, you need to register it with your main Flask application. This can be done by calling the register_blueprint() function on the Flask app instance:
app = Flask(__name__)
app.register_blueprint(my_blueprint)Now that we have our blueprint registered, let's define a route in our blueprint. For this, we'll use the add_url_rule() function:
@my_blueprint.route('/')
def home():
return 'Welcome to my_blueprint!'In the above example, we've created a route for the root URL (/) within our blueprint (my_blueprint). When a user navigates to this URL, the home() function will be called, and the returned string will be displayed.
Now that everything is set up, let's test our blueprint. To do this, run your Flask application and navigate to the URL you've defined in your blueprint's route.
Here's a complete example of a Flask application with a registered blueprint:
from flask import Flask, Blueprint, url_for
app = Flask(__name__)
my_blueprint = Blueprint('my_blueprint', __name__)
@my_blueprint.route('/')
def home():
return 'Welcome to my_blueprint!'
app.register_blueprint(my_blueprint)
if __name__ == '__main__':
app.run(debug=True)Which Flask function is used to define a route within a blueprint?
Stay tuned for our next lesson, where we'll dive deeper into Flask Blueprints, exploring how to pass data between blueprints, and more! 🚀