Skip to main content
1 of 5
davidh38
  • 181
  • 3
  • 10

Clean Architecture Python Example: How to implement a Usecase/Interactor saving Data to a Database

I am struggling with the clean architecure. I have constructed a minimal example of how a usecase/interactor could talk to the database without being dependent on it:

The use case:

class SaveDatatoDBUseCase:
def __init__(self, AbstractDB):
    self.db = AbstractDB

def execute(self):
    self.db.save()

The gateway:

from abc import ABC, abstractmethod    
class AbstractDB(ABC):

def __init__(self, value):
    pass

@abstractmethod
def save(self):
        pass

The Implementation for the Database:

class DBImplemtation(AbstractDB):
def __init__(self):
    pass

def save(self):
   print("INSERT INTO TABLE WHERE ...")

Wiring it altogether:

if __name__ == "__main__":
dbImpl = DBImplemtation()
save_to_db_Usecase = SaveDatatoDBUseCase(dbImpl)
save_to_db_Usecase.execute()

yields to:

INSERT INTO TABLE WHERE ...

Is this how the communcation works between the UseCase/Interactor and the Database or I am I missing something here? I added a picture to clarify what I wanted to achieve with the code.

Can someone please confirm, whether this is a good minimal approach and if not, where I got this wrong or even what could be improved. Thank you in advance. enter image description here

davidh38
  • 181
  • 3
  • 10