vendredi 11 août 2023

How should I structure modules in a large python application?

I often write and participate in the development of web applications in Python together with FastAPI. I always use the same folder structure which is as follows:

enter image description here

I think the names are clear to know what is in each of them. But I want to focus on two folders: api and services. Within api are all the modules with the endpoints of the application (one module for each "Entity", for example in the module api/routers/users.py will be all the endpoints for the users. In these endpoints there is no complex logic , all the logic is in the "services" folder. So, in the module services/users.py there will be a whole class called User with the logic. In many cases that class is simply a CRUD that inherits from a BASE CRUD and doesn't even extend the class Or maybe add one or two more methods. However, in some cases, the "entity" requires much more complex logic, it is appropriate to implement some design patterns, interfaces etc. When that happens I feel overwhelmed by having to put everything in the services/users.py module. (which implies a very large file). I've even seen how other developers continue to extend the User class (it's just an example, it can be anything) with a lot of methods that have nothing to do with the class, making the code too coupled and with low cohesion. As a solution to that, I thought of creating a folder as such for each entity and not a module. Then it would be services/user and there have all the user logic distributed in more than one module if necessary. But I'm not sure I'm doing the right thing in terms of design. Am I making things more complicated? Or is it a correct strategy?

Aucun commentaire:

Enregistrer un commentaire