Python DDD Example and Techniques
NOTE: This repository is an example to explain 'how to implement DDD architecture on a Python web application'. If you will to use this as a reference, add your implementation of authentication and security before deploying to the real world!!
Directory structure (based on Onion Architecture):
├── main.py
├── dddpy
│ ├── domain
│ │ └── book
│ ├── infrastructure
│ │ └── sqlite
│ │ ├── book
│ │ └── database.py
│ ├── presentation
│ │ └── schema
│ │ └── book
│ └── usecase
│ └── book
└── tests
To represent an Entity in Python, use __eq__()
method to ensure the object's itendity.
class Book:
def __init__(self, id: str, title: str):
self.id: str = id
self.title: str = title
def __eq__(self, o: object) -> bool:
if isinstance(o, Book):
return self.id == o.id
return False
To represent a Value Object, use @dataclass
decorator with eq=True
and frozen=True
.
The following code implements a book's ISBN code as a Value Object.
@dataclass(init=False, eq=True, frozen=True)
class Isbn:
value: str
def __init__(self, value: str):
if !validate_isbn(value):
raise ValueError("value should be valid ISBN format.")
object.__setattr__(self, "value", value)
DTO (Data Transfer Object) is a good practice to isolate domain objects from the infrastructure layer.
On a minimum MVC architecture, models often inherit a base class provided by an O/R Mapper. But in that case, the domain layer would be dependent on the outer layer.
To solve this problem, we can set two rules:
CQRS (Command and Query Responsibility Segregation) pattern is useful
Even if we succeed in isolating the domain layer, some issues remain. One of them is how to manage transactions.
UoW (Unit of Work) Pattern can be the solution.
First, define an interface base on UoW pattern in the usecase layer. begin()
, commit()
and rollback()
methods are related a transaction management.
class BookCommandUseCaseUnitOfWork(ABC):
book_repository: BookRepository
@abstractmethod
def begin(self):
raise NotImplementedError
@abstractmethod
def commit(self):
raise NotImplementedError
@abstractmethod
def rollback(self):
raise NotImplementedError
Second, implement a class of the infrastructure layer using the above interface.
class BookCommandUseCaseUnitOfWorkImpl(BookCommandUseCaseUnitOfWork):
def __init__(
self,
session: Session,
book_repository: BookRepository,
):
self.session: Session = session
self.book_repository: BookRepository = book_repository
def begin(self):
self.session.begin()
def commit(self):
self.session.commit()
def rollback(self):
self.session.rollback()
session
property is a session of SQLAlchemy,
make dev
on the Docker container terminalcurl --location --request POST 'localhost:8000/books' \
--header 'Content-Type: application/json' \
--data-raw '{
"isbn": "978-0321125217",
"title": "Domain-Driven Design: Tackling Complexity in the Heart of Software",
"page": 560
}'
{
"id": "HH9uqNdYbjScdiLgaTApcS",
"isbn": "978-0321125217",
"title": "Domain-Driven Design: Tackling Complexity in the Heart of Software",
"page": 560,
"read_page": 0,
"created_at": 1614007224642,
"updated_at": 1614007224642
}
curl --location --request GET 'localhost:8000/books'
[
{
"id": "e74R3Prx8SfcY8KJFkGVf3",
"isbn": "978-0321125217",
"title": "Domain-Driven Design: Tackling Complexity in the Heart of Software",
"page": 560,
"read_page": 0,
"created_at": 1614006055213,
"updated_at": 1614006055213
}
]