Welcome back to CodeYourCraft! Today, we're diving into the world of Flask Blueprints 🌈. This tutorial is designed for both beginners and intermediate learners, so let's get started!
Blueprints are a way of organizing our Flask application into reusable and modular components. They help manage large applications by dividing them into smaller, easier-to-manage parts.
Let's create a simple blueprint for a blog application.
from flask import Blueprint, request, render_template
blog = Blueprint('blog', __name__)
@blog.route('/')
def index():
return render_template('blog/index.html')
@blog.route('/about')
def about():
return render_template('blog/about.html')In the code above, we've created a blueprint named blog and registered it with the Flask app. We've also defined two routes for our blog's homepage and about page.
Blueprint('blog', __name__) creates a new blueprint named blog. The second argument is the name of the current module.@blog.route('/') is a decorator that tells Flask to handle requests for the root URL of our blueprint (/).render_template('blog/index.html') renders the HTML template for our blog's homepage.Now, let's register our blueprint in our main Flask app and test it out.
from flask import Flask
from my_app.blog import blog
app = Flask(__name__)
app.register_blueprint(blog)
if __name__ == '__main__':
app.run()In the code above, we've imported our blog blueprint and registered it with our Flask app. When we run our app, we should be able to access the blog homepage and about page by visiting http://localhost:5000/ and http://localhost:5000/about, respectively.
Question: Which function is responsible for rendering the HTML template for our blog's homepage?
A: index()
B: blog
C: render_template
Correct Answer: A
Explanation: The index() function is responsible for rendering the HTML template for our blog's homepage.
And there you have it! You've now created your first Flask Blueprint. In the next lesson, we'll dive deeper into blueprints and explore how to pass data between blueprints.
Stay tuned and happy coding! 💻🚀