• Stars
    star
    540
  • Rank 82,257 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created over 3 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python DDD Example and Techniques

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
    }
]

More Repositories

1

slackpy

A Simple and Human Friendly Slack Client for Logging.
Python
22
star
2

sphinx_theme_pd

CSS
20
star
3

hipchatpy

HipChat Client
Python
13
star
4

flutter-starter

for your next Flutter project ๐Ÿš€
Dart
10
star
5

youtube-url-parser

Parser for Youtube URL
TypeScript
10
star
6

ansible_playbooks

My Ansible Playbooks.
10
star
7

revcatgo

A helper library for integrating server-side apps with the RevenueCat webhook service.
Go
10
star
8

flutter_platformview_example

Examples of a Flutter PlatformView with Kotlin (Swift code is preparing)
Kotlin
9
star
9

slclogger

Simple and Human Friendly Slack Client for Logging Written in Go Programming Language
Go
9
star
10

gradient-mui-button

A Material-UI based modern gradient colors button component
JavaScript
8
star
11

sql-basic-book

ๆŠ€่ก“่ฉ•่ซ–็คพใ€Žใ“ใ‚Œใ‹ใ‚‰ใฏใ˜ใ‚ใ‚‹ SQL ๅ…ฅ้–€ใ€้–ข้€ฃๆƒ…ๅ ฑ & ใ‚ตใƒณใƒ—ใƒซใ‚ณใƒผใƒ‰ & ใƒ‡ใƒผใ‚ฟๅ…ฌ้–‹
SQLPL
6
star
12

react-component-lifecycle-diagram

5
star
13

fargon2

A plugin for generating a hash based on Argon2 algorithm in Android / iOS platform.
Dart
4
star
14

gihyo-book-scraper

Web scraping script to get books data from http://gihyo.jp/book/genre
Python
2
star
15

gis

GHOST IN THE SHELL (script)
Shell
2
star
16

whoami

Firebase Authentication JWT id Token Viewer
TypeScript
1
star
17

dart_iso_calendar

Dart package for calculating the year and week number based on ISO-8601.
Dart
1
star
18

hugo_theme_material_hugo

Material Hugo is a theme for Hugo.
CSS
1
star
19

flutter-ai-typing

A package to simulate AI typing text.
C++
1
star