All Projects → iktakahiro → dddpy

iktakahiro / dddpy

Licence: MIT license
Python DDD Example and Techniques

Programming Languages

python
139335 projects - #7 most used programming language
Makefile
30231 projects
Dockerfile
14818 projects

Projects that are alternatives of or similar to dddpy

dddplus-archetype-demo
♨️ Using dddplus-archetype build a WMS in 5 minutes. 5分钟搭建一个仓储中台WMS!
Stars: ✭ 56 (-84.82%)
Mutual labels:  ddd-architecture, ddd-example
typescript-ddd-course
🔷🔖 TypeScript DDD Course: Learn Domain-Driven Design in TS lesson by lesson
Stars: ✭ 28 (-92.41%)
Mutual labels:  ddd-architecture, ddd-example
csharp-ddd-skeleton
🦈✨ C# DDD Skeleton: Bootstrap your new C# projects applying Hexagonal Architecture and Domain-Driven Design patterns
Stars: ✭ 67 (-81.84%)
Mutual labels:  ddd-architecture, ddd-example
typescript-ddd-example
🔷🎯 TypeScript DDD Example: Complete project applying Hexagonal Architecture and Domain-Driven Design patterns
Stars: ✭ 607 (+64.5%)
Mutual labels:  ddd-architecture, ddd-example
Modular Monolith With Ddd
Full Modular Monolith application with Domain-Driven Design approach.
Stars: ✭ 6,210 (+1582.93%)
Mutual labels:  ddd-architecture, ddd-example
Library
A microservice project using .NET Core 2.0, DDD, CQRS, Event Sourcing, Redis and RabbitMQ
Stars: ✭ 122 (-66.94%)
Mutual labels:  ddd-architecture
Run Aspnetcore Realworld
E-Commerce real world example of run-aspnetcore ASP.NET Core web application. Implemented e-commerce domain with clean architecture for ASP.NET Core reference application, demonstrating a layered application architecture with DDD best practices. Download 100+ page eBook PDF from here ->
Stars: ✭ 208 (-43.63%)
Mutual labels:  ddd-architecture
Base App Nestjs
Base application using nest JS focused on DDD architecture and SOLID principles
Stars: ✭ 115 (-68.83%)
Mutual labels:  ddd-architecture
Comboost
ComBoost是一个领域驱动的快速开发框架
Stars: ✭ 111 (-69.92%)
Mutual labels:  ddd-architecture
Ddd
A Domain Driven Design framework for software simplicity in node
Stars: ✭ 244 (-33.88%)
Mutual labels:  ddd-architecture
Library
This is a project of a library, driven by real business requirements. We use techniques strongly connected with Domain Driven Design, Behavior-Driven Development, Event Storming, User Story Mapping.
Stars: ✭ 2,685 (+627.64%)
Mutual labels:  ddd-architecture
Nlayerappv3
Domain Driven Design (DDD) N-LayeredArchitecture with .Net Core 2
Stars: ✭ 138 (-62.6%)
Mutual labels:  ddd-architecture
Run Aspnetcore
A starter kit for your next ASP.NET Core web application. Boilerplate for ASP.NET Core reference application, demonstrating a layered application architecture with applying Clean Architecture and DDD best practices. Download 100+ page eBook PDF from here ->
Stars: ✭ 227 (-38.48%)
Mutual labels:  ddd-architecture
Milkomeda
Spring extend componets which build from experience of bussiness, let developers to develop with Spring Boot as fast as possible.(基于Spring生态打造的一系列来自业务上的快速开发模块集合。)
Stars: ✭ 117 (-68.29%)
Mutual labels:  ddd-architecture
Netcorekit
💗 A crafted toolkit for building cloud-native apps on the .NET platform
Stars: ✭ 248 (-32.79%)
Mutual labels:  ddd-architecture
Nim Basolato
An asynchronous fullstack web framework for Nim.
Stars: ✭ 111 (-69.92%)
Mutual labels:  ddd-architecture
Symfony Ddd Wishlist
Wishlist, a sample application on Symfony 3 and Vue.js built with DDD in mind
Stars: ✭ 172 (-53.39%)
Mutual labels:  ddd-architecture
Typescript Ddd Skeleton
🟨 TypeScript DDD Skeleton: Bootstrap your new projects or be inspired by this example project
Stars: ✭ 240 (-34.96%)
Mutual labels:  ddd-architecture
Event Sourcing Jambo
An Hexagonal Architecture with DDD + Aggregates + Event Sourcing using .NET Core, Kafka e MongoDB (Blog Engine)
Stars: ✭ 159 (-56.91%)
Mutual labels:  ddd-architecture
Php Ddd Skeleton
🐘🚀 PHP DDD Skeleton: Bootstrap your new projects or be inspired by this example project
Stars: ✭ 152 (-58.81%)
Mutual labels:  ddd-architecture

Python DDD Example and Techniques

A workflow to run test

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!!

Tech Stack

Code Architecture

Directory structure (based on Onion Architecture):

├── main.py
├── dddpy
│   ├── domain
│   │   └── book
│   ├── infrastructure
│   │   └── sqlite
│   │       ├── book
│   │       └── database.py
│   ├── presentation
│   │   └── schema
│   │       └── book
│   └── usecase
│       └── book
└── tests

Entity

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

Value Object

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)

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:

  1. Domain layer classes (such as an Entity or a Value Object) DO NOT extend SQLAlchemy Base class.
  2. Data transfer Objects extend the O/R mapper class.

CQRS

CQRS (Command and Query Responsibility Segregation) pattern is useful

UoW (Unit of Work)

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,

How to work

  1. Clone and open this repository using VSCode
  2. Run Remote-Container
  3. Run make dev on the Docker container terminal
  4. Access the API document http://127.0.0.1:8000/docs

OpenAPI Doc

Sample requests for the RESTFul API

  • Create a new book:
curl --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
}'
  • Response of the POST request:
{
    "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
}
  • Get books:
curl --location --request GET 'localhost:8000/books'
  • Response of the GET request:
[
    {
        "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
    }
]
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].