Зміст курсу
Professional Web API with Flask
Professional Web API with Flask
Start with Blueprints and MethodViews
Modularizing Our Project:
To keep our project simple and usable, we employ modularity, dividing functionality across files and packages. We will now create a separate 'resources' folder for all our future endpoint files. Within this folder, we will create four files: team.py, player.py, club.py, and user.py.
Setting Up Blueprints:
In team.py, we begin by setting up our Blueprint corresponding to our model:
We will do the same for each subsequent model. The first argument names our blueprint, the second indicates in which module our blueprint is identified, and the last argument, the description, will be seen in our Swagger documentation.
Defining Our Class-Based Views:
Using Flask's MethodView, we define class-based views to handle different HTTP methods:
This structure neatly encapsulates the HTTP methods for the Team model. The dynamic URL responds to either fetching information about a single team or deleting it, while the second URL handles listing teams or creating a new one.
Repeating the Structure for Other Models:
We follow the same structure according to the needs and logic of our application for models like Club and Player.
Imagine we do not require any more functionality for the club model because we are creating a separate service for one team. The only thing we do is return information about this club.
Registering Our Blueprints:
In addition to defining our views, we must register our blueprints for each model:
In app.py, after initializing our API, we register our blueprints, which integrate the defined endpoints into the application.
Дякуємо за ваш відгук!