Let's define our very first blueprint for the admin functionality inside the admin/routes.py file: from flask import Blueprint Now that you understand what problems Blueprints solves, let's see how we can use Blueprints in our applications. The logic related to admin resides inside the admin folder, the logic related to products resides inside the products folder and so on.Īdditionally, we also separated the templates and static files in the subdirectories where they are required, so that irrelevant files don't load when going to a page that doesn't require them. Now you can see that you have clear separation of concerns. So, with Blueprints now your same application will look like this: /blueprint-tutorial In addition to that, you can store your templates and static files along with the logic in the same subdirectory. Blueprints help you structure your application by organizing the logic into subdirectories. Now, this is where Flask Blueprints come into picture. Let's look at the app.py file: from flask import Flaskĭoesn't that look messy (imagining that you've built a large-scale app)? You have all your models and different routes inside the same file spread around here and there. If you follow the Flask documentation to create a minimal application, your project structure will look similar to this: /myappĭoesn't the folder look so clean? All you have is an app.py file where you have all your logic for the application, a templates folder to store your HTML files, and a static folder to store your static files. In Flask, also, you can organize your applications using Blueprints, a built-in concept in Flask similar to Python modules. If you have worked with Django, you might have found your project divided into different modules. But it's not a good practice for a large-scale app.īy doing this, you are clearly violating the Single Responsibility Principle, where each piece of your application should handle just one responsibility. You will find a lot of tutorials that follow the same pattern. Sometimes you'll find developers dumping all of their logic into a single file called app.py. Flask is a simple, easy-to-use microframework for Python that can help you build scalable and secure web applications.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |