├── .env.example ├── .flake8 ├── .gitignore ├── .pre-commit-config.yaml ├── .pylintrc ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yaml ├── requirements.txt ├── src ├── __init__.py ├── adapters │ ├── __init__.py │ └── rest_adapter.py ├── app.py ├── database │ └── __init__.py ├── dependency.py ├── domain │ ├── __init__.py │ ├── base │ │ ├── __init__.py │ │ ├── entity.py │ │ ├── event.py │ │ ├── model.py │ │ ├── ports │ │ │ ├── __init__.py │ │ │ └── event_adapter_interface.py │ │ └── value_object.py │ ├── delivery │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ └── cost_calculator_adapter.py │ │ └── ports │ │ │ ├── __init__.py │ │ │ └── cost_calculator_interface.py │ ├── maps │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ └── google_maps_adapter.py │ │ ├── ports │ │ │ ├── __init__.py │ │ │ └── maps_adapter_interface.py │ │ └── value_objects.py │ ├── order │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ └── order_event_publisher_adapter.py │ │ ├── controllers │ │ │ ├── __init__.py │ │ │ └── order_controller.py │ │ ├── entities.py │ │ ├── events.py │ │ ├── exceptions │ │ │ ├── __init__.py │ │ │ └── order_exceptions.py │ │ ├── ports │ │ │ ├── __init__.py │ │ │ ├── order_database_interface.py │ │ │ └── order_service_interface.py │ │ ├── repository │ │ │ ├── __init__.py │ │ │ └── order_repository.py │ │ ├── schemas │ │ │ ├── __init__.py │ │ │ └── order_schemas.py │ │ ├── services │ │ │ ├── __init__.py │ │ │ └── order_service.py │ │ └── value_objects.py │ ├── payment │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ └── paypal_adapter.py │ │ ├── ports │ │ │ ├── __init__.py │ │ │ └── payment_adapter_interface.py │ │ └── value_objects.py │ └── product │ │ ├── __init__.py │ │ ├── adapters │ │ ├── __init__.py │ │ └── product_adapter.py │ │ ├── entities.py │ │ ├── ports │ │ ├── __init__.py │ │ └── product_adapter_interface.py │ │ └── value_objects.py ├── event_handler.py ├── exceptions.py ├── main.py ├── schemas.py └── settings.py └── tests └── __init__.py /.env.example: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/.env.example -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = .git, *migrations*, manage.py, ignore/, venv, *_pb2* 3 | max-line-length = 100 4 | extend-ignore = E203, E0401 5 | per-file-ignores = 6 | __init__.py:F401 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | .idea 132 | .DS_Store 133 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/.pre-commit-config.yaml -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # Analyse import fallback blocks. This can be used to support both Python 2 and 4 | # 3 compatible code, which means that the block might have code that exists 5 | # only in one or another interpreter, leading to false positives when analysed. 6 | analyse-fallback-blocks=no 7 | 8 | # Load and enable all available extensions. Use --list-extensions to see a list 9 | # all available extensions. 10 | #enable-all-extensions= 11 | 12 | # In error mode, messages with a category besides ERROR or FATAL are 13 | # suppressed, and no reports are done by default. Error mode is compatible with 14 | # disabling specific errors. 15 | #errors-only= 16 | 17 | # Always return a 0 (non-error) status code, even if lint errors are found. 18 | # This is primarily useful in continuous integration scripts. 19 | #exit-zero= 20 | 21 | # A comma-separated list of package or module names from where C extensions may 22 | # be loaded. Extensions are loading into the active Python interpreter and may 23 | # run arbitrary code. 24 | extension-pkg-allow-list= 25 | 26 | # A comma-separated list of package or module names from where C extensions may 27 | # be loaded. Extensions are loading into the active Python interpreter and may 28 | # run arbitrary code. (This is an alternative name to extension-pkg-allow-list 29 | # for backward compatibility.) 30 | extension-pkg-whitelist= 31 | 32 | # Return non-zero exit code if any of these messages/categories are detected, 33 | # even if score is above --fail-under value. Syntax same as enable. Messages 34 | # specified are enabled, while categories only check already-enabled messages. 35 | fail-on= 36 | 37 | # Specify a score threshold to be exceeded before program exits with error. 38 | fail-under=10 39 | 40 | # Interpret the stdin as a python script, whose filename needs to be passed as 41 | # the module_or_package argument. 42 | #from-stdin= 43 | 44 | # Files or directories to be skipped. They should be base names, not paths. 45 | ignore=CVS 46 | 47 | # Add files or directories matching the regex patterns to the ignore-list. The 48 | # regex matches against paths and can be in Posix or Windows format. 49 | ignore-paths=migrations,tests,mocks 50 | 51 | # Files or directories matching the regex patterns are skipped. The regex 52 | # matches against base names, not paths. The default value ignores Emacs file 53 | # locks 54 | ignore-patterns=^\.# 55 | 56 | # List of module names for which member attributes should not be checked 57 | # (useful for modules/projects where namespaces are manipulated during runtime 58 | # and thus existing member attributes cannot be deduced by static analysis). It 59 | # supports qualified module names, as well as Unix pattern matching. 60 | ignored-modules= 61 | 62 | # Python code to execute, usually for sys.path manipulation such as 63 | # pygtk.require(). 64 | #init-hook= 65 | 66 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the 67 | # number of processors available to use. 68 | jobs=1 69 | 70 | # Control the amount of potential inferred values when inferring a single 71 | # object. This can help the performance when dealing with large functions or 72 | # complex, nested conditions. 73 | limit-inference-results=100 74 | 75 | # List of plugins (as comma separated values of python module names) to load, 76 | # usually to register additional checkers. 77 | load-plugins=pylint_pydantic 78 | 79 | # Pickle collected data for later comparisons. 80 | persistent=yes 81 | 82 | # Minimum Python version to use for version dependent checks. Will default to 83 | # the version used to run pylint. 84 | py-version=3.10 85 | 86 | # Discover python modules and packages in the file system subtree. 87 | recursive=no 88 | 89 | # When enabled, pylint would attempt to guess common misconfiguration and emit 90 | # user-friendly hints instead of false-positive error messages. 91 | suggestion-mode=yes 92 | 93 | # Allow loading of arbitrary C extensions. Extensions are imported into the 94 | # active Python interpreter and may run arbitrary code. 95 | unsafe-load-any-extension=no 96 | 97 | # In verbose mode, extra non-checker-related info will be displayed. 98 | #verbose= 99 | 100 | 101 | [REPORTS] 102 | 103 | # Python expression which should return a score less than or equal to 10. You 104 | # have access to the variables 'fatal', 'error', 'warning', 'refactor', 105 | # 'convention', and 'info' which contain the number of messages in each 106 | # category, as well as 'statement' which is the total number of statements 107 | # analyzed. This score is used by the global evaluation report (RP0004). 108 | evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) 109 | 110 | # Template used to display messages. This is a python new-style format string 111 | # used to format the message information. See doc for all details. 112 | msg-template= 113 | 114 | # Set the output format. Available formats are text, parseable, colorized, json 115 | # and msvs (visual studio). You can also give a reporter class, e.g. 116 | # mypackage.mymodule.MyReporterClass. 117 | output-format=parseable 118 | 119 | # Tells whether to display a full report or only the messages. 120 | reports=no 121 | 122 | # Activate the evaluation score. 123 | score=yes 124 | 125 | 126 | [MESSAGES CONTROL] 127 | 128 | # Only show warnings with the listed confidence levels. Leave empty to show 129 | # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, 130 | # UNDEFINED. 131 | confidence= 132 | 133 | # Disable the message, report, category or checker with the given id(s). You 134 | # can either give multiple identifiers separated by comma (,) or put this 135 | # option multiple times (only on the command line, not in the configuration 136 | # file where it should appear only once). You can also use "--disable=all" to 137 | # disable everything first and then re-enable specific checks. For example, if 138 | # you want to run only the similarities checker, you can use "--disable=all 139 | # --enable=similarities". If you want to run only the classes checker, but have 140 | # no Warning level messages displayed, use "--disable=all --enable=classes 141 | # --disable=W". 142 | disable= 143 | E0401, # Unable to import 144 | C0114, # missing-module-docstring 145 | C0115, # missing-class-docstring 146 | C0116, # missing-function-docstring 147 | W0511, # todos 148 | E0601, # used-before-assignment 149 | W0150, # lost-exception 150 | W0703, # broad-except 151 | C0413, # wrong-import-order 152 | W0613, # unused-argument 153 | W0611, # unused-import 154 | W0105, # pointles-string-statement 155 | E0110, # abstract-class-instantiated 156 | C0201, # consider-using-enumerate 157 | C0411, # wrong-import-order 158 | C0301, # line-too-long 159 | R0903, # too-few-public-methods 160 | R1710, # inconsistent-return-statements, 161 | C0412, # ungrouped-imports, 162 | E0611, # no-name-in-module, 163 | C0103, # invalid-name 164 | R0914, # too-many-locals 165 | R0913, # too-many-arguments 166 | R0902, # too-many-instance-attributes 167 | W0201, # attribute-defined-outside-init 168 | C0415, # import-outside-toplevel 169 | R0912, # too-many-branches, 170 | R0915, # too-many-statements 171 | R0801, 172 | invalid-unary-operand-type, 173 | raw-checker-failed, 174 | bad-inline-option, 175 | locally-disabled, 176 | file-ignored, 177 | suppressed-message, 178 | useless-suppression, 179 | deprecated-pragma, 180 | use-symbolic-message-instead, 181 | no-member, 182 | too-many-public-methods 183 | 184 | # Enable the message, report, category or checker with the given id(s). You can 185 | # either give multiple identifier separated by comma (,) or put this option 186 | # multiple time (only on the command line, not in the configuration file where 187 | # it should appear only once). See also the "--disable" option for examples. 188 | enable=c-extension-no-member 189 | 190 | 191 | [LOGGING] 192 | 193 | # The type of string formatting that logging methods do. `old` means using % 194 | # formatting, `new` is for `{}` formatting. 195 | ; logging-format-style=old 196 | 197 | # Logging modules to check that the string format arguments are in logging 198 | # function parameter format. 199 | logging-modules=logging 200 | 201 | 202 | [SPELLING] 203 | 204 | # Limits count of emitted suggestions for spelling mistakes. 205 | max-spelling-suggestions=4 206 | 207 | # Spelling dictionary name. Available dictionaries: none. To make it work, 208 | # install the 'python-enchant' package. 209 | spelling-dict= 210 | 211 | # List of comma separated words that should be considered directives if they 212 | # appear at the beginning of a comment and should not be checked. 213 | spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: 214 | 215 | # List of comma separated words that should not be checked. 216 | spelling-ignore-words= 217 | 218 | # A path to a file that contains the private dictionary; one word per line. 219 | spelling-private-dict-file= 220 | 221 | # Tells whether to store unknown words to the private dictionary (see the 222 | # --spelling-private-dict-file option) instead of raising a message. 223 | spelling-store-unknown-words=no 224 | 225 | 226 | [MISCELLANEOUS] 227 | 228 | # List of note tags to take in consideration, separated by a comma. 229 | notes=FIXME, 230 | XXX, 231 | TODO 232 | 233 | # Regular expression of note tags to take in consideration. 234 | notes-rgx= 235 | 236 | 237 | [TYPECHECK] 238 | 239 | # Tells whether missing members accessed in mixin class should be ignored. A 240 | # mixin class is detected if its name ends with "mixin" (case insensitive). 241 | ignore-mixin-members=yes 242 | 243 | # List of decorators that produce context managers, such as 244 | # contextlib.contextmanager. Add to this list to register other decorators that 245 | # produce valid context managers. 246 | contextmanager-decorators=contextlib.contextmanager 247 | 248 | # List of members which are set dynamically and missed by pylint inference 249 | # system, and so shouldn't trigger E1101 when accessed. Python regular 250 | # expressions are accepted. 251 | generated-members= 252 | 253 | # Tells whether to warn about missing members when the owner of the attribute 254 | # is inferred to be None. 255 | ignore-none=yes 256 | 257 | # This flag controls whether pylint should warn about no-member and similar 258 | # checks whenever an opaque object is returned when inferring. The inference 259 | # can return multiple potential results while evaluating a Python object, but 260 | # some branches might not be evaluated, which results in partial inference. In 261 | # that case, it might be useful to still emit no-member and other checks for 262 | # the rest of the inferred objects. 263 | ignore-on-opaque-inference=yes 264 | 265 | # List of symbolic message names to ignore for Mixin members. 266 | ignored-checks-for-mixins=no-member, 267 | not-async-context-manager, 268 | not-context-manager, 269 | attribute-defined-outside-init 270 | 271 | # List of class names for which member attributes should not be checked (useful 272 | # for classes with dynamically set attributes). This supports the use of 273 | # qualified names. 274 | ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace 275 | 276 | # Show a hint with possible names when a member name was not found. The aspect 277 | # of finding the hint is based on edit distance. 278 | missing-member-hint=yes 279 | 280 | # The minimum edit distance a name should have in order to be considered a 281 | # similar match for a missing member name. 282 | missing-member-hint-distance=1 283 | 284 | # The total number of similar names that should be taken in consideration when 285 | # showing a hint for a missing member. 286 | missing-member-max-choices=1 287 | 288 | # Regex pattern to define which classes are considered mixins. 289 | mixin-class-rgx=.*[Mm]ixin 290 | 291 | # List of decorators that change the signature of a decorated function. 292 | signature-mutators= 293 | 294 | 295 | [CLASSES] 296 | 297 | # Warn about protected attribute access inside special methods 298 | check-protected-access-in-special-methods=no 299 | 300 | # List of method names used to declare (i.e. assign) instance attributes. 301 | defining-attr-methods=__init__, 302 | __new__, 303 | setUp, 304 | __post_init__ 305 | 306 | # List of member names, which should be excluded from the protected access 307 | # warning. 308 | exclude-protected=_asdict, 309 | _fields, 310 | _replace, 311 | _source, 312 | _make 313 | 314 | # List of valid names for the first argument in a class method. 315 | valid-classmethod-first-arg=cls 316 | 317 | # List of valid names for the first argument in a metaclass class method. 318 | valid-metaclass-classmethod-first-arg=cls 319 | 320 | 321 | [VARIABLES] 322 | 323 | # List of additional names supposed to be defined in builtins. Remember that 324 | # you should avoid defining new builtins when possible. 325 | additional-builtins= 326 | 327 | # Tells whether unused global variables should be treated as a violation. 328 | allow-global-unused-variables=yes 329 | 330 | # List of names allowed to shadow builtins 331 | allowed-redefined-builtins= 332 | 333 | # List of strings which can identify a callback function by name. A callback 334 | # name must start or end with one of those strings. 335 | callbacks=cb_, 336 | _cb 337 | 338 | # A regular expression matching the name of dummy variables (i.e. expected to 339 | # not be used). 340 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 341 | 342 | # Argument names that match this expression will be ignored. Default to name 343 | # with leading underscore. 344 | ignored-argument-names=_.*|^ignored_|^unused_ 345 | 346 | # Tells whether we should check for unused import in __init__ files. 347 | init-import=no 348 | 349 | # List of qualified module names which can have objects that can redefine 350 | # builtins. 351 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io 352 | 353 | 354 | [FORMAT] 355 | 356 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 357 | expected-line-ending-format= 358 | 359 | # Regexp for a line that is allowed to be longer than the limit. 360 | ignore-long-lines=^\s*(# )??$ 361 | 362 | # Number of spaces of indent required inside a hanging or continued line. 363 | indent-after-paren=4 364 | 365 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 366 | # tab). 367 | indent-string=' ' 368 | 369 | # Maximum number of characters on a single line. 370 | max-line-length=100 371 | 372 | # Maximum number of lines in a module. 373 | max-module-lines=1000 374 | 375 | # Allow the body of a class to be on the same line as the declaration if body 376 | # contains single statement. 377 | single-line-class-stmt=no 378 | 379 | # Allow the body of an if to be on the same line as the test if there is no 380 | # else. 381 | single-line-if-stmt=no 382 | 383 | 384 | [IMPORTS] 385 | 386 | # List of modules that can be imported at any level, not just the top level 387 | # one. 388 | allow-any-import-level= 389 | 390 | # Allow wildcard imports from modules that define __all__. 391 | allow-wildcard-with-all=no 392 | 393 | # Deprecated modules which should not be used, separated by a comma. 394 | deprecated-modules= 395 | 396 | # Output a graph (.gv or any supported image format) of external dependencies 397 | # to the given file (report RP0402 must not be disabled). 398 | ext-import-graph= 399 | 400 | # Output a graph (.gv or any supported image format) of all (i.e. internal and 401 | # external) dependencies to the given file (report RP0402 must not be 402 | # disabled). 403 | import-graph= 404 | 405 | # Output a graph (.gv or any supported image format) of internal dependencies 406 | # to the given file (report RP0402 must not be disabled). 407 | int-import-graph= 408 | 409 | # Force import order to recognize a module as part of the standard 410 | # compatibility libraries. 411 | known-standard-library= 412 | 413 | # Force import order to recognize a module as part of a third party library. 414 | known-third-party=enchant 415 | 416 | # Couples of modules and preferred modules, separated by a comma. 417 | preferred-modules= 418 | 419 | 420 | [EXCEPTIONS] 421 | 422 | # Exceptions that will emit a warning when caught. 423 | overgeneral-exceptions=BaseException, 424 | Exception, 425 | CommonExceptions 426 | 427 | 428 | [REFACTORING] 429 | 430 | # Maximum number of nested blocks for function / method body 431 | max-nested-blocks=5 432 | 433 | # Complete name of functions that never returns. When checking for 434 | # inconsistent-return-statements if a never returning function is called then 435 | # it will be considered as an explicit return statement and no message will be 436 | # printed. 437 | never-returning-functions=sys.exit,argparse.parse_error 438 | 439 | 440 | [SIMILARITIES] 441 | # Comments are removed from the similarity computation 442 | ignore-comments=yes 443 | 444 | # Docstrings are removed from the similarity computation 445 | ignore-docstrings=yes 446 | 447 | # Imports are removed from the similarity computation 448 | ignore-imports=yes 449 | 450 | # Signatures are removed from the similarity computation 451 | ignore-signatures=yes 452 | 453 | # Minimum lines number of a similarity. 454 | min-similarity-lines=4 455 | 456 | 457 | [DESIGN] 458 | 459 | # List of regular expressions of class ancestor names to ignore when counting 460 | # public methods (see R0903) 461 | exclude-too-few-public-methods= 462 | 463 | # List of qualified class names to ignore when counting class parents (see 464 | # R0901) 465 | ignored-parents= 466 | 467 | # Maximum number of arguments for function / method. 468 | max-args=5 469 | 470 | # Maximum number of attributes for a class (see R0902). 471 | max-attributes=7 472 | 473 | # Maximum number of boolean expressions in an if statement (see R0916). 474 | max-bool-expr=5 475 | 476 | # Maximum number of branch for function / method body. 477 | max-branches=12 478 | 479 | # Maximum number of locals for function / method body. 480 | max-locals=15 481 | 482 | # Maximum number of parents for a class (see R0901). 483 | max-parents=7 484 | 485 | # Maximum number of public methods for a class (see R0904). 486 | max-public-methods=20 487 | 488 | # Maximum number of return / yield for function / method body. 489 | max-returns=6 490 | 491 | # Maximum number of statements in function / method body. 492 | max-statements=50 493 | 494 | # Minimum number of public methods for a class (see R0903). 495 | min-public-methods=2 496 | 497 | 498 | [STRING] 499 | 500 | # This flag controls whether inconsistent-quotes generates a warning when the 501 | # character used as a quote delimiter is used inconsistently within a module. 502 | check-quote-consistency=no 503 | 504 | # This flag controls whether the implicit-str-concat should generate a warning 505 | # on implicit string concatenation in sequences defined over several lines. 506 | check-str-concat-over-line-jumps=no 507 | 508 | 509 | [BASIC] 510 | 511 | # Naming style matching correct argument names. 512 | argument-naming-style=snake_case 513 | 514 | # Regular expression matching correct argument names. Overrides argument- 515 | # naming-style. If left empty, argument names will be checked with the set 516 | # naming style. 517 | #argument-rgx= 518 | 519 | # Naming style matching correct attribute names. 520 | attr-naming-style=snake_case 521 | 522 | # Regular expression matching correct attribute names. Overrides attr-naming- 523 | # style. If left empty, attribute names will be checked with the set naming 524 | # style. 525 | #attr-rgx= 526 | 527 | # Bad variable names which should always be refused, separated by a comma. 528 | bad-names=foo, 529 | bar, 530 | baz, 531 | toto, 532 | tutu, 533 | tata 534 | 535 | # Bad variable names regexes, separated by a comma. If names match any regex, 536 | # they will always be refused 537 | bad-names-rgxs= 538 | 539 | # Naming style matching correct class attribute names. 540 | class-attribute-naming-style=any 541 | 542 | # Regular expression matching correct class attribute names. Overrides class- 543 | # attribute-naming-style. If left empty, class attribute names will be checked 544 | # with the set naming style. 545 | #class-attribute-rgx= 546 | 547 | # Naming style matching correct class constant names. 548 | class-const-naming-style=UPPER_CASE 549 | 550 | # Regular expression matching correct class constant names. Overrides class- 551 | # const-naming-style. If left empty, class constant names will be checked with 552 | # the set naming style. 553 | #class-const-rgx= 554 | 555 | # Naming style matching correct class names. 556 | class-naming-style=PascalCase 557 | 558 | # Regular expression matching correct class names. Overrides class-naming- 559 | # style. If left empty, class names will be checked with the set naming style. 560 | #class-rgx= 561 | 562 | # Naming style matching correct constant names. 563 | const-naming-style=UPPER_CASE 564 | 565 | # Regular expression matching correct constant names. Overrides const-naming- 566 | # style. If left empty, constant names will be checked with the set naming 567 | # style. 568 | #const-rgx= 569 | 570 | # Minimum line length for functions/classes that require docstrings, shorter 571 | # ones are exempt. 572 | docstring-min-length=-1 573 | 574 | # Naming style matching correct function names. 575 | function-naming-style=snake_case 576 | 577 | # Regular expression matching correct function names. Overrides function- 578 | # naming-style. If left empty, function names will be checked with the set 579 | # naming style. 580 | #function-rgx= 581 | 582 | # Good variable names which should always be accepted, separated by a comma. 583 | good-names=i, 584 | j, 585 | k, 586 | ex, 587 | Run, 588 | _, 589 | logger, 590 | T 591 | 592 | # Good variable names regexes, separated by a comma. If names match any regex, 593 | # they will always be accepted 594 | good-names-rgxs= 595 | 596 | # Include a hint for the correct naming format with invalid-name. 597 | include-naming-hint=no 598 | 599 | # Naming style matching correct inline iteration names. 600 | inlinevar-naming-style=any 601 | 602 | # Regular expression matching correct inline iteration names. Overrides 603 | # inlinevar-naming-style. If left empty, inline iteration names will be checked 604 | # with the set naming style. 605 | #inlinevar-rgx= 606 | 607 | # Naming style matching correct method names. 608 | method-naming-style=snake_case 609 | 610 | # Regular expression matching correct method names. Overrides method-naming- 611 | # style. If left empty, method names will be checked with the set naming style. 612 | #method-rgx= 613 | 614 | # Naming style matching correct module names. 615 | module-naming-style=snake_case 616 | 617 | # Regular expression matching correct module names. Overrides module-naming- 618 | # style. If left empty, module names will be checked with the set naming style. 619 | #module-rgx= 620 | 621 | # Colon-delimited sets of names that determine each other's naming style when 622 | # the name regexes allow several styles. 623 | name-group= 624 | 625 | # Regular expression which should only match function or class names that do 626 | # not require a docstring. 627 | no-docstring-rgx=^_ 628 | 629 | # List of decorators that produce properties, such as abc.abstractproperty. Add 630 | # to this list to register other decorators that produce valid properties. 631 | # These decorators are taken in consideration only for invalid-name. 632 | property-classes=abc.abstractproperty 633 | 634 | # Regular expression matching correct type variable names. If left empty, type 635 | # variable names will be checked with the set naming style. 636 | #typevar-rgx= 637 | 638 | # Naming style matching correct variable names. 639 | variable-naming-style=snake_case 640 | 641 | # Regular expression matching correct variable names. Overrides variable- 642 | # naming-style. If left empty, variable names will be checked with the set 643 | # naming style. 644 | #variable-rgx= 645 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10 2 | 3 | RUN mkdir /code 4 | WORKDIR /code 5 | 6 | ENV PYTHONUNBUFFERED 1 7 | 8 | ADD requirements.txt /code/ 9 | RUN pip install -r requirements.txt 10 | 11 | ADD . /code/ 12 | 13 | CMD python src/main.py 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | rest-up: 2 | docker-compose -f rest.docker-compose.yml up --build 3 | 4 | rest-down: 5 | docker-compose -f rest.docker-compose.yml down 6 | 7 | test-domain: 8 | pytest tests/domain/ 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hexagonal-architecture-with-python 2 | Applying pattern Ports and Adapters with Python Fastapi. 3 | 4 | 5 | ## Bounded Contexts 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
Domain:Ordering
Concepts:Domain Driven Design (Subdomains, Bounded Contexts, Ubiquitous Language, Aggregates, Entities and Value Objects)
Architecture style:Event Driven Microservices
Architectural patterns:Eventsourcing, Hexagonal Architecture
25 | 26 | ## Domain 27 | Customers use the website application(s) to place orders. Application coordinates order preparation and delivery. 28 | 29 | ## Sub-domains 30 | - **Order**: This domain is responsible for managing and processing orders placed by customers, including product selection, pricing, and payment completion. 31 | - **Product**: This domain is responsible for managing and providing information about the products available for sale, including descriptions, prices and images. 32 | - **Delivery**: This domain is responsible for managing and tracking deliveries, including scheduling deliveries, tracking carrier location, and processing returns. 33 | - **Maps**: This domain is responsible for providing geographic information including delivery routes, delivery locations and estimated travel time. 34 | - **Payment**: This domain is responsible for processing payments, including credit card authorizations, balance checks and payment confirmations 35 | 36 | 37 | ## Domain model 38 | 39 | Sub-domain *software programing* models: 40 | 41 | - [ordering](https://github.com/marcosvs98/hexagonal-architecture-with-python/tree/main/src/domain) 42 | 43 | > Domain model is mainly a software programing model which is applied to a specific sub-domain. 44 | > It defines the vocabulary and acts as a communication tool for everyone involved (business and IT), deriving a [Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html). 45 | 46 | ## Bounded Context 47 | 48 | Each of this group of applications/services belongs to a specific bounded context: 49 | - [ordering](https://github.com/marcosvs98/hexagonal-architecture-with-python/tree/main/src/domain) - Order bounded context, with messages serialized to JSON 50 | 51 | 52 | > A goal is to develop a [Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html) as our domain (sub-domain) model within an explicitly Bounded Context. 53 | > Therefore, there are a number of rules for Models and Contexts 54 | > - Explicitly define the context within which a model applies 55 | > - Ideally, keep one sub-domain model per one Bounded Context 56 | > - Explicitly set boundaries in terms of team organization, usage within specific parts of the application, and physical manifestations such as code bases and database schemas 57 | 58 | 59 | 60 | ## Technologies and patterns used 61 | 62 | - **Python 3.9** 63 | - **FastAPI (Rest API)** 64 | - **MongoDB** 65 | 66 | This project has a structure that aims at the maximum decoupling between layers in order to give 67 | support for creating components that are reusable across the entire business domain. It has a simple User CRUD with 68 | examples of package organization and tests. 69 | 70 | In addition to others, the main pattern that guides this project is the Hexagonal (+ Clean Architecture), in short, this pattern 71 | provides a way to organize code so that the business logic is encapsulated, but separate from the underlying engine. 72 | delivery. This allows for better maintenance and fewer dependencies. 73 | 74 | 75 | --- 76 | ## Running the project 77 | 78 | ### Option 1 - Via Docker Compose 79 | 80 | #### Run docker-compose 81 | 82 | Finally, run the project and its dependencies in the background using the command 83 | ```bash 84 | docker-compose up -d 85 | ``` 86 | 87 | ## References 88 | 89 | - [Hexagonal Architecture](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/) 90 | - [Domain Driven Design - DDD](https://lyz-code.github.io/blue-book/architecture/domain_driven_design/) 91 | - [Repository Pattern](https://lyz-code.github.io/blue-book/architecture/repository_pattern/) 92 | - [Service Layer Pattern](https://www.cosmicpython.com/book/chapter_04_service_layer.html) 93 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.1' 2 | 3 | services: 4 | ordering-service: 5 | build: 6 | dockerfile: Dockerfile 7 | context: . 8 | volumes: 9 | - .:/code 10 | env_file: 11 | - .env 12 | ports: 13 | - '8090:8090' 14 | environment: 15 | MONGO_SERVER: event-source-mongo-db 16 | MONGO_PORT: '27017' 17 | MONGO_USERNAME: root 18 | MONGO_PASSWORD: admin 19 | restart: always 20 | 21 | event-source-mongo-db: 22 | image: mongo:5.0 23 | container_name: event-source-mongo-db 24 | environment: 25 | MONGO_INITDB_ROOT_USERNAME: root 26 | MONGO_INITDB_ROOT_PASSWORD: admin 27 | ports: 28 | - '27017:27017' 29 | restart: always 30 | 31 | mongo-db-express: 32 | image: mongo-express 33 | container_name: mongo-db-express 34 | restart: unless-stopped 35 | ports: 36 | - 8081:8081 37 | environment: 38 | ME_CONFIG_OPTIONS_EDITORTHEME: dracula 39 | ME_CONFIG_MONGODB_URL: mongodb://root:admin@event-source-mongo-db:27017/ 40 | depends_on: 41 | - event-source-mongo-db 42 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aioredis==2.0.1 2 | dnspython>=2.1.0,<2.2.0 3 | fastapi>=0.68.1,<0.69.0 4 | fastapi_pagination==0.9.3 5 | motor>=2.5.1,<2.6.0 6 | pydantic>=1.8.2,<1.9.0 7 | pymongo>=3.12.0,<3.13.0 8 | python-decouple==3.6 9 | SQLAlchemy==1.4.41 10 | uvicorn==0.13.4 11 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/__init__.py -------------------------------------------------------------------------------- /src/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/adapters/__init__.py -------------------------------------------------------------------------------- /src/adapters/rest_adapter.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | from fastapi import FastAPI, Request 3 | from fastapi.middleware.cors import CORSMiddleware 4 | from fastapi.responses import JSONResponse 5 | 6 | import event_handler 7 | from settings import MongoDatabaseSettings 8 | from exceptions import CommonException 9 | from schemas import HealthCheck 10 | 11 | from domain.order.controllers.order_controller import OrderController 12 | from domain.order.repository.order_repository import OrderDatabaseRepository 13 | from domain.order.services.order_service import OrderService 14 | from domain.payment.adapters.paypal_adapter import PayPalPaymentAdapter 15 | from domain.product.adapters.product_adapter import ProductAdapter 16 | from domain.delivery.adapters.cost_calculator_adapter import DeliveryCostCalculatorAdapter 17 | from domain.maps.adapters.google_maps_adapter import GoogleMapsAdapter 18 | from domain.order.adapters.order_event_publisher_adapter import OrderEventPublisher 19 | 20 | 21 | def init_middlewares(app: FastAPI): 22 | app.add_middleware( 23 | CORSMiddleware, 24 | allow_origins=['*'], 25 | allow_credentials=False, 26 | allow_methods=['*'], 27 | allow_headers=['*'], 28 | ) 29 | 30 | 31 | def init_routes(app: FastAPI): 32 | @app.get('/', status_code=200, response_model=HealthCheck) 33 | async def health_check(): 34 | return {'status': 200} 35 | 36 | app.state.event_source_config = MongoDatabaseSettings() 37 | app.add_event_handler('startup', func=partial(event_handler.startup, app=app)) 38 | app.add_event_handler('shutdown', func=partial(event_handler.shutdown, app=app)) 39 | 40 | app.include_router( 41 | OrderController( 42 | OrderService( 43 | repository=OrderDatabaseRepository(), 44 | payment_service=PayPalPaymentAdapter(), 45 | product_service=ProductAdapter(), 46 | delivery_service=DeliveryCostCalculatorAdapter(maps_service=GoogleMapsAdapter()), 47 | event_publisher=OrderEventPublisher(), 48 | ) 49 | ).router, 50 | tags=['order'], 51 | prefix='/api/v1/order', 52 | ) 53 | 54 | @app.exception_handler(CommonException) 55 | async def service_exception_handler(request: Request, error: CommonException): 56 | return JSONResponse(error.to_dict(), status_code=error.code) 57 | -------------------------------------------------------------------------------- /src/app.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from fastapi_pagination import add_pagination 3 | from settings import APPLICATION_NAME 4 | from adapters.rest_adapter import init_routes, init_middlewares 5 | 6 | 7 | def create_app(): 8 | app = FastAPI( 9 | title=APPLICATION_NAME, 10 | description='FastAPI application using hexagonal architecture', 11 | ) 12 | 13 | init_middlewares(app) 14 | init_routes(app) 15 | add_pagination(app) 16 | 17 | return app 18 | -------------------------------------------------------------------------------- /src/database/__init__.py: -------------------------------------------------------------------------------- 1 | import motor.motor_asyncio 2 | from settings import MongoDatabaseSettings 3 | 4 | 5 | def get_mongo_db(config: MongoDatabaseSettings): 6 | uri = f'mongodb://{config.MONGO_USERNAME}:{config.MONGO_PASSWORD}@{config.MONGO_SERVER}:{config.MONGO_PORT}' # noqa: E501 7 | client = motor.motor_asyncio.AsyncIOMotorClient(uri) 8 | db = client.OrderingService 9 | return db 10 | -------------------------------------------------------------------------------- /src/dependency.py: -------------------------------------------------------------------------------- 1 | from fastapi import Request 2 | 3 | 4 | async def get_mongo_db(request: Request): 5 | mongo_db = request.app.state.mongo_db 6 | return mongo_db 7 | -------------------------------------------------------------------------------- /src/domain/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/__init__.py -------------------------------------------------------------------------------- /src/domain/base/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/base/__init__.py -------------------------------------------------------------------------------- /src/domain/base/entity.py: -------------------------------------------------------------------------------- 1 | from domain.base.model import Model 2 | 3 | 4 | class Entity(Model): 5 | """Base class for domain entitie objects.""" 6 | 7 | def __str__(self): 8 | return f'{type(self).__name__}' 9 | 10 | def __repr__(self): 11 | return self.__str__() 12 | 13 | 14 | class AggregateRoot(Entity): 15 | """Base class for domain aggregate objects. Consits of 1+ entities""" 16 | -------------------------------------------------------------------------------- /src/domain/base/event.py: -------------------------------------------------------------------------------- 1 | from domain.base.model import Model 2 | 3 | 4 | class DomainEvent(Model): 5 | """Base class for domain events objects""" 6 | 7 | @classmethod 8 | def domain_event_name(cls): 9 | return cls.__name__ 10 | 11 | def __eq__(self, other: 'DomainEvent'): 12 | if type(self) is not type(other): 13 | return False 14 | return self.serialize() == other.serialize() 15 | 16 | class Config: 17 | arbitrary_types_allowed = True 18 | -------------------------------------------------------------------------------- /src/domain/base/model.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Extra 2 | 3 | 4 | class Model(BaseModel, extra=Extra.allow): 5 | """Base class for model objects""" 6 | -------------------------------------------------------------------------------- /src/domain/base/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/base/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/base/ports/event_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from domain.base.event import DomainEvent 3 | 4 | 5 | class DomainEventPublisher(metaclass=abc.ABCMeta): 6 | """Base domain event publisher.""" 7 | 8 | @abc.abstractmethod 9 | async def publish(self, event: DomainEvent): 10 | raise NotImplementedError 11 | -------------------------------------------------------------------------------- /src/domain/base/value_object.py: -------------------------------------------------------------------------------- 1 | from typing import TypeVar 2 | from domain.base.model import Model 3 | from pydantic import validator 4 | 5 | ImplementationType = TypeVar('ImplementationType', bound='ValueObject') 6 | 7 | 8 | class ValueObject(Model): 9 | """Base class for value objects""" 10 | 11 | def __eq__(self: ImplementationType, other: ImplementationType): 12 | if type(self) is not type(other): 13 | return False 14 | 15 | for attr_name in getattr(self, '__attrs'): 16 | if getattr(self, attr_name) != getattr(other, attr_name): 17 | return False 18 | 19 | return True 20 | 21 | class Config: 22 | arbitrary_types_allowed = True 23 | 24 | 25 | class StrIdValueObject(ValueObject): 26 | """Base class for string value objects""" 27 | 28 | value: str 29 | 30 | def __init__(self, value): # noqa: W0622: 31 | super().__init__(value=value) 32 | 33 | def __repr__(self): 34 | return str(self) 35 | 36 | def __str__(self): 37 | return str(self.value) 38 | 39 | @validator('*') 40 | def validate(cls, value): 41 | if isinstance(value, StrIdValueObject): 42 | return str(value) 43 | return value 44 | -------------------------------------------------------------------------------- /src/domain/delivery/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/delivery/__init__.py -------------------------------------------------------------------------------- /src/domain/delivery/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/delivery/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/delivery/adapters/cost_calculator_adapter.py: -------------------------------------------------------------------------------- 1 | from domain.maps.value_objects import Address 2 | from domain.maps.ports.maps_adapter_interface import MapsAdapterInterface 3 | from domain.delivery.ports.cost_calculator_interface import ( 4 | DeliveryCostCalculatorAdapterInterface, 5 | ) # noqa: E501 6 | 7 | ORDER_PRICE_THRESHOLD = 500.0 8 | FREE_DISTANCE_THRESHOLD = 10.0 9 | FREE = 0.0 10 | FLAT_PRICE = 50.0 11 | BASE_PRICE = 50.0 12 | FREE_DISTANCE_THRESHOLD = 30.0 13 | PRICE_PER_EXTRA_DISTANCE = 15.0 14 | 15 | 16 | class DeliveryCostCalculatorAdapter(DeliveryCostCalculatorAdapterInterface): 17 | def __init__(self, maps_service: MapsAdapterInterface): 18 | self.maps_service = maps_service 19 | 20 | async def calculate_cost(self, total_product_cost: float, destination: Address) -> float: 21 | if total_product_cost >= ORDER_PRICE_THRESHOLD: 22 | return await self._large_delivery_calculate_cost(destination) 23 | return await self._small_delivery_calculate_cost(destination) 24 | 25 | async def _large_delivery_calculate_cost(self, destination: Address) -> float: 26 | distance_from_warehouse = await self.maps_service.calculate_distance_from_warehouses( 27 | destination 28 | ) 29 | 30 | if ( 31 | destination.bangkok_and_surrounding() 32 | or distance_from_warehouse <= FREE_DISTANCE_THRESHOLD 33 | ): 34 | return FREE 35 | 36 | return FLAT_PRICE 37 | 38 | async def _small_delivery_calculate_cost(self, destination: Address) -> float: 39 | distance_from_warehouse = await self.maps_service.calculate_distance_from_warehouses( 40 | destination 41 | ) 42 | 43 | if distance_from_warehouse <= FREE_DISTANCE_THRESHOLD: 44 | return BASE_PRICE 45 | 46 | distance_extra = distance_from_warehouse - FREE_DISTANCE_THRESHOLD 47 | cost_extra = PRICE_PER_EXTRA_DISTANCE * distance_extra 48 | 49 | return BASE_PRICE + cost_extra 50 | -------------------------------------------------------------------------------- /src/domain/delivery/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/delivery/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/delivery/ports/cost_calculator_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from domain.maps.value_objects import Address 3 | from domain.maps.ports.maps_adapter_interface import MapsAdapterInterface 4 | 5 | 6 | class DeliveryCostCalculatorAdapterInterface(abc.ABC): 7 | @abc.abstractmethod 8 | def __init__(self, maps_service: MapsAdapterInterface): 9 | raise NotImplementedError 10 | 11 | @abc.abstractmethod 12 | async def calculate_cost(self, total_product_cost: float, destination: Address) -> float: 13 | raise NotImplementedError 14 | 15 | @abc.abstractmethod 16 | async def _large_delivery_calculate_cost(self, destination: Address) -> float: 17 | raise NotImplementedError 18 | 19 | @abc.abstractmethod 20 | async def _small_delivery_calculate_cost(self, destination: Address) -> float: 21 | raise NotImplementedError 22 | -------------------------------------------------------------------------------- /src/domain/maps/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/maps/__init__.py -------------------------------------------------------------------------------- /src/domain/maps/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/maps/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/maps/adapters/google_maps_adapter.py: -------------------------------------------------------------------------------- 1 | from domain.maps.ports.maps_adapter_interface import MapsAdapterInterface 2 | from domain.maps.value_objects import Address 3 | 4 | 5 | class GoogleMapsAdapter(MapsAdapterInterface): 6 | async def calculate_distance_from_warehouses(self, destination: Address) -> float: 7 | house_number = str(destination.house_number).split('/', maxsplit=1)[0] 8 | return float(house_number) 9 | -------------------------------------------------------------------------------- /src/domain/maps/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/maps/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/maps/ports/maps_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from domain.maps.value_objects import Address 3 | 4 | 5 | class MapsAdapterInterface(abc.ABC): 6 | @abc.abstractmethod 7 | async def calculate_distance_from_warehouses(self, destination: Address) -> float: 8 | raise NotImplementedError 9 | -------------------------------------------------------------------------------- /src/domain/maps/value_objects.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from domain.base.value_object import ValueObject 3 | from pydantic import validator 4 | 5 | 6 | class StatesEnum(str, Enum): 7 | RS: str = 'Rio Grande do Sul' 8 | SP: str = 'São Paulo' 9 | SC: str = 'Santa Catarina' 10 | 11 | @classmethod 12 | def has_value(cls, value): 13 | return value in cls._member_map_.values() 14 | 15 | 16 | class State(ValueObject): 17 | enum: str = StatesEnum 18 | 19 | def states(self) -> bool: 20 | return self.value in [state.value for state in StatesEnum] 21 | 22 | @validator('enum', check_fields=False) 23 | def validate(cls, value): 24 | if not StatesEnum.has_value(value): 25 | raise ValueError(f'State named "{value}" not exists') 26 | return value 27 | 28 | 29 | class Address(ValueObject): 30 | house_number: str 31 | road: str 32 | sub_district: str 33 | district: str 34 | state: str 35 | postcode: str 36 | country: str 37 | 38 | def states(self) -> bool: 39 | return self.state.states() 40 | -------------------------------------------------------------------------------- /src/domain/order/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/__init__.py -------------------------------------------------------------------------------- /src/domain/order/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/order/adapters/order_event_publisher_adapter.py: -------------------------------------------------------------------------------- 1 | from database import get_mongo_db 2 | from settings import MongoDatabaseSettings 3 | from domain.base.event import DomainEvent 4 | from domain.base.ports.event_adapter_interface import DomainEventPublisher 5 | 6 | 7 | class OrderEventPublisher(DomainEventPublisher): 8 | def __init__(self, collection_name='order_events'): 9 | self.event_source = get_mongo_db(MongoDatabaseSettings()) 10 | self.collection_name = collection_name 11 | 12 | async def publish(self, event: DomainEvent): 13 | await self.event_source[self.collection_name].insert_one(event.dict()) 14 | -------------------------------------------------------------------------------- /src/domain/order/controllers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/controllers/__init__.py -------------------------------------------------------------------------------- /src/domain/order/controllers/order_controller.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, HTTPException, Request 2 | from domain.order.ports.order_service_interface import OrderServiceInterface 3 | 4 | from domain.order.value_objects import BuyerId 5 | from domain.order.value_objects import OrderId 6 | 7 | 8 | from domain.order.exceptions.order_exceptions import ( 9 | OrderAlreadyPaidException, 10 | OrderAlreadyCancelledException, 11 | PaymentNotVerifiedException, 12 | ) 13 | 14 | 15 | from domain.order.schemas.order_schemas import ( 16 | OrderCreateRequest, 17 | OrderCreateResponse, 18 | OrderDetail, 19 | OrderUpdateStatusRequest, 20 | OrderStatus, 21 | OrderUpdateStatusResponse, 22 | ) 23 | 24 | 25 | class OrderController: 26 | def __init__(self, order_service: OrderServiceInterface): 27 | self.service = order_service 28 | self.router = APIRouter() 29 | self.router.add_api_route( 30 | '/', self.create_order, methods=['POST'], response_model=OrderCreateResponse 31 | ) # noqa: E501 32 | self.router.add_api_route( 33 | '/{order_id}', self.get_order, methods=['GET'], response_model=OrderDetail 34 | ) # noqa: F541 35 | self.router.add_api_route( 36 | '/{order_id}', 37 | self.update_order, 38 | methods=['PATCH'], 39 | response_model=OrderUpdateStatusResponse, 40 | ) # noqa: F541 41 | 42 | async def create_order(self, request: Request, order: OrderCreateRequest): 43 | buyer_id = BuyerId(order.buyer_id) 44 | order_id = await self.service.create_new_order(buyer_id, order.items, order.destination) 45 | return OrderCreateResponse(order_id=str(order_id)) 46 | 47 | async def get_order(self, request: Request, order_id): 48 | order = await self.service.get_order_from_id(order_id=order_id) 49 | return OrderDetail.from_order(order) 50 | 51 | async def update_order( 52 | self, request: Request, order_id, order_status: OrderUpdateStatusRequest 53 | ): 54 | order_id = OrderId(order_id) 55 | 56 | if order_status.status == OrderStatus.paid: 57 | await self._pay_order(order_id) 58 | order = OrderUpdateStatusResponse(order_id=str(order_id), status='paid') 59 | elif order_status.status == OrderStatus.cancelled: 60 | await self._cancel_order(order_id) 61 | order = OrderUpdateStatusResponse(order_id=str(order_id), status='cancelled') 62 | else: 63 | error_detail = f"Cannot update Order's status to {order_status.status}" 64 | raise HTTPException(status_code=403, detail=error_detail) 65 | return order 66 | 67 | async def _pay_order(self, order_id: OrderId): 68 | try: 69 | return await self.service.pay_order(order_id) 70 | except OrderAlreadyCancelledException as e: 71 | error_detail = "Cannot pay for Order when it's already cancelled" 72 | raise HTTPException(status_code=409, detail=error_detail) from e 73 | except OrderAlreadyPaidException as e: 74 | error_detail = "Cannot pay for Order when it's already paid" 75 | raise HTTPException(status_code=409, detail=error_detail) from e 76 | except PaymentNotVerifiedException as e: 77 | error_detail = 'Payment verification failed' 78 | raise HTTPException(status_code=403, detail=error_detail) from e 79 | 80 | async def _cancel_order(self, order_id: OrderId): 81 | try: 82 | return await self.service.cancel_order(order_id) 83 | except OrderAlreadyCancelledException as e: 84 | error_detail = "Cannot cancel Order when it's already cancelled" 85 | raise HTTPException(status_code=409, detail=error_detail) from e 86 | except OrderAlreadyPaidException as e: 87 | error_detail = "Cannot cancel Order when it's already paid" 88 | raise HTTPException(status_code=409, detail=error_detail) from e 89 | -------------------------------------------------------------------------------- /src/domain/order/entities.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | from domain.base.entity import AggregateRoot 4 | from domain.payment.value_objects import PaymentId 5 | from domain.order.value_objects import OrderId 6 | from domain.order.value_objects import BuyerId 7 | from domain.order.value_objects import OrderItem 8 | from domain.order.value_objects import OrderStatus 9 | from domain.order.exceptions.order_exceptions import ( 10 | OrderAlreadyCancelledException, 11 | OrderAlreadyPaidException, 12 | PaymentNotVerifiedException, 13 | ) 14 | 15 | 16 | class Order(AggregateRoot): 17 | order_id: OrderId 18 | buyer_id: BuyerId 19 | items: List[OrderItem] 20 | product_cost: float 21 | delivery_cost: float 22 | payment_id: PaymentId 23 | status: OrderStatus = OrderStatus.Enum.WAITING 24 | version: int = 0 25 | 26 | def pay(self, is_payment_verified: bool): 27 | if self.is_cancelled(): 28 | raise OrderAlreadyCancelledException(detail="Order's already cancelled") 29 | if self.is_paid(): 30 | raise OrderAlreadyPaidException(detail="Order's already paid") 31 | if not is_payment_verified: 32 | raise PaymentNotVerifiedException(detail=f'Payment {self.payment_id} must be verified') 33 | 34 | self.status = OrderStatus.Enum.PAID 35 | 36 | def cancel(self): 37 | if self.is_cancelled(): 38 | raise OrderAlreadyCancelledException(detail="Order's already cancelled") 39 | if self.is_paid(): 40 | raise OrderAlreadyPaidException(detail="Order's already paid") 41 | 42 | self.status = OrderStatus.Enum.CANCELLED 43 | 44 | def is_waiting(self) -> bool: 45 | return self._get_order_status(self.status).is_waiting() 46 | 47 | def is_paid(self) -> bool: 48 | return self._get_order_status(self.status).is_paid() 49 | 50 | def is_cancelled(self) -> bool: 51 | return self._get_order_status(self.status).is_cancelled() 52 | 53 | def _get_order_status(self, value): 54 | return OrderStatus(value) 55 | 56 | @property 57 | def total_cost(self) -> float: 58 | return self.product_cost + self.delivery_cost 59 | 60 | def increase_version(self): 61 | self.version += 1 62 | 63 | class Config: 64 | arbitrary_types_allowed = True 65 | -------------------------------------------------------------------------------- /src/domain/order/events.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import List 3 | from pydantic import Field 4 | from domain.base.event import DomainEvent 5 | from domain.maps.value_objects import Address 6 | 7 | from domain.payment.value_objects import PaymentId 8 | from domain.order.value_objects import OrderId 9 | from domain.order.value_objects import BuyerId 10 | from domain.order.value_objects import OrderItem 11 | 12 | 13 | class OrderEventName(Enum): 14 | 15 | CREATED = 'payment_order_created' 16 | CANCELLED = 'payment_order_cancelled' 17 | PAID = 'payment_order_paid' 18 | 19 | 20 | class OrderCreated(DomainEvent): 21 | event_name: str = Field(OrderEventName.CREATED.value) 22 | order_id: OrderId 23 | buyer_id: BuyerId 24 | items: List[OrderItem] 25 | product_cost: float 26 | delivery_cost: float 27 | payment_id: PaymentId 28 | destination: Address 29 | version: int = 0 30 | 31 | 32 | class OrderPaid(DomainEvent): 33 | event_name: str = Field(OrderEventName.PAID.value) 34 | order_id: OrderId 35 | buyer_id: BuyerId 36 | items: List[OrderItem] 37 | product_cost: float 38 | delivery_cost: float 39 | payment_id: PaymentId 40 | version: int = 0 41 | 42 | 43 | class OrderCancelled(DomainEvent): 44 | event_name: str = Field(OrderEventName.CANCELLED.value) 45 | order_id: OrderId 46 | buyer_id: BuyerId 47 | items: List[OrderItem] 48 | product_cost: float 49 | delivery_cost: float 50 | payment_id: PaymentId 51 | version: int = 0 52 | 53 | 54 | class OrderEvent(Enum): 55 | """Domain Event raised for special order use cases""" 56 | 57 | CREATED = 'CREATED' 58 | CANCELLED = 'CANCELLED' 59 | PAID = 'PAID' 60 | -------------------------------------------------------------------------------- /src/domain/order/exceptions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/exceptions/__init__.py -------------------------------------------------------------------------------- /src/domain/order/exceptions/order_exceptions.py: -------------------------------------------------------------------------------- 1 | from exceptions import CommonException 2 | 3 | 4 | class OrderAlreadyCancelledException(CommonException): 5 | pass 6 | 7 | 8 | class OrderAlreadyPaidException(CommonException): 9 | pass 10 | 11 | 12 | class PaymentNotVerifiedException(CommonException): 13 | pass 14 | 15 | 16 | class EntityNotFound(CommonException): 17 | pass 18 | 19 | 20 | class EntityOutdated(CommonException): 21 | pass 22 | -------------------------------------------------------------------------------- /src/domain/order/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/order/ports/order_database_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from typing import List 3 | from domain.order.value_objects import OrderId 4 | from domain.order.entities import Order 5 | 6 | 7 | class OrderDatabaseInterface(abc.ABC): 8 | @abc.abstractmethod 9 | def __init__(self): 10 | raise NotImplementedError 11 | 12 | @abc.abstractmethod 13 | async def next_identity(self) -> OrderId: 14 | raise NotImplementedError 15 | 16 | @abc.abstractmethod 17 | async def all(self) -> List[Order]: 18 | raise NotImplementedError 19 | 20 | @abc.abstractmethod 21 | async def from_id(self, id_: OrderId) -> Order: 22 | raise NotImplementedError 23 | 24 | @abc.abstractmethod 25 | async def save(self, entity: Order): 26 | raise NotImplementedError 27 | -------------------------------------------------------------------------------- /src/domain/order/ports/order_service_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from typing import List 3 | 4 | from domain.order.value_objects import BuyerId, OrderItem, OrderId 5 | from domain.order.entities import Order 6 | from domain.maps.value_objects import Address 7 | 8 | from domain.order.ports.order_database_interface import OrderDatabaseInterface # noqa: E501 9 | from domain.payment.ports.payment_adapter_interface import PaymentAdapterInterface # noqa: E501 10 | from domain.product.ports.product_adapter_interface import ProductAdapterInterface # noqa: E501 11 | from domain.delivery.ports.cost_calculator_interface import ( 12 | DeliveryCostCalculatorAdapterInterface, 13 | ) # noqa: E501 14 | from domain.base.ports.event_adapter_interface import DomainEventPublisher # noqa: E501 15 | 16 | 17 | class OrderServiceInterface(abc.ABC): 18 | 19 | repository: OrderDatabaseInterface 20 | 21 | @abc.abstractmethod 22 | def __init__( 23 | self, 24 | repository: OrderDatabaseInterface, 25 | payment_service: PaymentAdapterInterface, 26 | product_service: ProductAdapterInterface, 27 | delivery_service: DeliveryCostCalculatorAdapterInterface, 28 | event_publisher: DomainEventPublisher, 29 | ): 30 | raise NotImplementedError 31 | 32 | @abc.abstractmethod 33 | async def create_new_order( 34 | self, buyer_id: BuyerId, items: List[OrderItem], destination: Address 35 | ) -> OrderId: 36 | raise NotImplementedError 37 | 38 | @abc.abstractmethod 39 | async def pay_order(self, order_id: OrderId): 40 | raise NotImplementedError 41 | 42 | @abc.abstractmethod 43 | async def cancel_order(self, order_id: OrderId): 44 | raise NotImplementedError 45 | 46 | @abc.abstractmethod 47 | async def get_order_from_id(self, order_id: OrderId) -> Order: 48 | raise NotImplementedError 49 | 50 | @abc.abstractmethod 51 | async def _pay_order_tnx(self, order_id, is_payment_verified): 52 | raise NotImplementedError 53 | -------------------------------------------------------------------------------- /src/domain/order/repository/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/repository/__init__.py -------------------------------------------------------------------------------- /src/domain/order/repository/order_repository.py: -------------------------------------------------------------------------------- 1 | from database import get_mongo_db 2 | from settings import MongoDatabaseSettings 3 | from typing import List 4 | from bson.objectid import ObjectId 5 | from pymongo.errors import DuplicateKeyError 6 | from domain.order.ports.order_database_interface import OrderDatabaseInterface # noqa: E501 7 | from domain.order.value_objects import OrderId 8 | from domain.order.entities import Order 9 | from domain.order.exceptions.order_exceptions import EntityOutdated 10 | 11 | 12 | class OrderDatabaseRepository(OrderDatabaseInterface): 13 | def __init__(self, collection_name='order'): 14 | self.db = get_mongo_db(MongoDatabaseSettings()) 15 | self.collection_name = collection_name 16 | 17 | async def next_identity(self) -> OrderId: 18 | return OrderId(str(ObjectId())) 19 | 20 | async def all(self, limit=10) -> List[Order]: 21 | raw_list = await self.db[self.collection_name].find().to_list(limit) 22 | return [Order.deserialize(raw) for raw in raw_list] 23 | 24 | async def from_id(self, order_id: OrderId) -> Order: 25 | raw = await self.db[self.collection_name].find_one({'_id': ObjectId(str(order_id))}) 26 | del raw['_id'] 27 | return Order(**raw) 28 | 29 | async def save(self, entity: Order): 30 | data = entity.dict() 31 | order_id = ObjectId(str(entity.order_id)) 32 | 33 | spec = {'_id': order_id, 'version': entity.version} 34 | update = {'$set': data, '$inc': {'version': 1}} 35 | del data['version'] 36 | 37 | try: 38 | await self.db[self.collection_name].update_one(spec, update, upsert=True) 39 | except DuplicateKeyError as e: 40 | raise EntityOutdated(detail=f'Order with OrderId {order_id} is not dated') from e 41 | -------------------------------------------------------------------------------- /src/domain/order/schemas/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/schemas/__init__.py -------------------------------------------------------------------------------- /src/domain/order/schemas/order_schemas.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | from typing import List 3 | from enum import Enum 4 | from bson import ObjectId 5 | from pydantic import BaseModel 6 | from domain.order.entities import Order 7 | from domain.order.value_objects import OrderId 8 | from domain.order.value_objects import BuyerId 9 | from domain.payment.value_objects import PaymentId 10 | 11 | 12 | class Address(BaseModel): 13 | house_number: str 14 | road: str 15 | sub_district: str 16 | district: str 17 | state: str 18 | postcode: str 19 | country: str 20 | 21 | class Config: 22 | schema_extra = { 23 | 'example': { 24 | 'house_number': '70', 25 | 'road': 'Rua Afonso Charlier', 26 | 'sub_district': 'SUB_DISTRICT', 27 | 'district': 'Porto Alegre', 28 | 'state': 'RS', 29 | 'postcode': '92310010', 30 | 'country': 'Brazil', 31 | } 32 | } 33 | 34 | 35 | class OrderItem(BaseModel): 36 | product_id: str 37 | amount: int 38 | 39 | class Config: 40 | schema_extra = { 41 | 'example': { 42 | 'product_id': str(ObjectId()), 43 | 'amount': 20, 44 | } 45 | } 46 | 47 | 48 | class OrderCreateRequest(BaseModel): 49 | buyer_id: BuyerId 50 | items: List[OrderItem] 51 | destination: Address 52 | 53 | class Config: 54 | schema_extra = { 55 | 'example': { 56 | 'buyer_id': str(ObjectId()), 57 | 'items': [OrderItem.schema()['example']], 58 | 'destination': Address.schema()['example'], 59 | } 60 | } 61 | 62 | 63 | class OrderCreateResponse(BaseModel): 64 | order_id: OrderId 65 | 66 | class Config: 67 | schema_extra = { 68 | 'example': { 69 | 'order_id': str(ObjectId()), 70 | } 71 | } 72 | 73 | 74 | class OrderStatus(str, Enum): 75 | waiting: str = 'waiting' 76 | paid: str = 'paid' 77 | cancelled: str = 'cancelled' 78 | 79 | 80 | class OrderUpdateStatusRequest(BaseModel): 81 | status: str 82 | 83 | class Config: 84 | schema_extra = {'example': {'status': 'paid'}} 85 | 86 | 87 | class OrderUpdateStatusResponse(BaseModel): 88 | order_id: OrderId 89 | status: OrderStatus 90 | 91 | class Config: 92 | schema_extra = { 93 | 'example': { 94 | 'order_id': str(ObjectId()), 95 | 'status': 'paid', 96 | } 97 | } 98 | 99 | @classmethod 100 | def from_order_id(cls, order_id: OrderId): 101 | return cls(order_id=str(order_id)) 102 | 103 | 104 | class OrderDetail(BaseModel): 105 | buyer_id: BuyerId 106 | payment_id: PaymentId 107 | items: List[OrderItem] 108 | 109 | product_cost: float 110 | delivery_cost: float 111 | total_cost: float 112 | status: OrderStatus 113 | 114 | class Config: 115 | schema_extra = { 116 | 'example': { 117 | 'buyer_id': str(ObjectId()), 118 | 'payment_id': str(uuid.uuid4()), 119 | 'items': [OrderItem.schema()['example']], 120 | 'product_cost': 424.2, 121 | 'delivery_cost': 42.42, 122 | 'total_cost': 466.62, 123 | 'status': 'waiting', 124 | } 125 | } 126 | 127 | @classmethod 128 | def from_order(cls, order: Order): 129 | return cls(**order.dict(), total_cost=order.total_cost) 130 | -------------------------------------------------------------------------------- /src/domain/order/services/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/order/services/__init__.py -------------------------------------------------------------------------------- /src/domain/order/services/order_service.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | from domain.order.value_objects import BuyerId, OrderItem, OrderId 4 | from domain.order.entities import Order 5 | from domain.maps.value_objects import Address 6 | 7 | from domain.order.ports.order_service_interface import OrderServiceInterface # noqa: E501 8 | from domain.order.ports.order_database_interface import OrderDatabaseInterface # noqa: E501 9 | from domain.payment.ports.payment_adapter_interface import PaymentAdapterInterface # noqa: E501 10 | from domain.product.ports.product_adapter_interface import ProductAdapterInterface # noqa: E501 11 | from domain.delivery.ports.cost_calculator_interface import ( 12 | DeliveryCostCalculatorAdapterInterface, 13 | ) # noqa: E501 14 | from domain.base.ports.event_adapter_interface import DomainEventPublisher 15 | from domain.order.events import OrderCreated, OrderPaid, OrderCancelled 16 | 17 | 18 | class OrderService(OrderServiceInterface): 19 | 20 | repository: OrderDatabaseInterface 21 | 22 | def __init__( 23 | self, 24 | repository: OrderDatabaseInterface, 25 | payment_service: PaymentAdapterInterface, 26 | product_service: ProductAdapterInterface, 27 | delivery_service: DeliveryCostCalculatorAdapterInterface, 28 | event_publisher: DomainEventPublisher, 29 | ): 30 | self.repository = repository 31 | self.payment_service = payment_service 32 | self.product_service = product_service 33 | self.delivery_service = delivery_service 34 | self.event_publisher = event_publisher 35 | 36 | async def create_new_order( 37 | self, buyer_id: BuyerId, items: List[OrderItem], destination: Address 38 | ) -> OrderId: 39 | 40 | product_counts = [(item.product_id, int(item.amount)) for item in items] 41 | total_product_cost = await self.product_service.total_price(product_counts) 42 | payment_id = await self.payment_service.new_payment(total_product_cost) 43 | delivery_cost = await self.delivery_service.calculate_cost(total_product_cost, destination) 44 | order_id = await self.repository.next_identity() 45 | 46 | order = Order( 47 | order_id=order_id, 48 | buyer_id=buyer_id, 49 | items=items, 50 | product_cost=float(total_product_cost), 51 | delivery_cost=float(delivery_cost), 52 | payment_id=payment_id, 53 | ) 54 | await self.repository.save(order) 55 | 56 | event = OrderCreated( 57 | order_id=order_id, 58 | buyer_id=buyer_id, 59 | items=items, 60 | product_cost=total_product_cost, 61 | delivery_cost=delivery_cost, 62 | payment_id=payment_id, 63 | destination=destination, 64 | ) 65 | 66 | await self.event_publisher.publish(event) 67 | 68 | return order.order_id 69 | 70 | async def pay_order(self, order_id: OrderId): 71 | order = await self.repository.from_id(order_id=order_id) 72 | payment_id = order.payment_id 73 | 74 | is_payment_verified = await self.payment_service.verify_payment(payment_id=payment_id) 75 | await self._pay_order_tnx(order_id, is_payment_verified) 76 | 77 | async def cancel_order(self, order_id: OrderId): 78 | order = await self.repository.from_id(order_id) 79 | order.cancel() 80 | 81 | event = OrderCancelled( 82 | order_id=order.order_id, 83 | buyer_id=order.buyer_id, 84 | items=order.items, 85 | product_cost=order.product_cost, 86 | delivery_cost=order.delivery_cost, 87 | payment_id=order.payment_id, 88 | version=order.version, 89 | ) 90 | 91 | await self.event_publisher.publish(event) 92 | await self.repository.save(order) 93 | 94 | async def get_order_from_id(self, order_id: OrderId) -> Order: 95 | return await self.repository.from_id(order_id) 96 | 97 | async def _pay_order_tnx(self, order_id, is_payment_verified): 98 | order = await self.repository.from_id(order_id=order_id) 99 | order.pay(is_payment_verified=is_payment_verified) 100 | 101 | event = OrderPaid( 102 | order_id=order.order_id, 103 | buyer_id=order.buyer_id, 104 | items=order.items, 105 | product_cost=order.product_cost, 106 | delivery_cost=order.delivery_cost, 107 | payment_id=order.payment_id, 108 | version=order.version, 109 | ) 110 | await self.event_publisher.publish(event) 111 | await self.repository.save(order) 112 | -------------------------------------------------------------------------------- /src/domain/order/value_objects.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import Union 3 | 4 | from pydantic import validator 5 | from domain.base.value_object import ValueObject, StrIdValueObject 6 | 7 | 8 | class OrderStatusEnum(str, Enum): 9 | WAITING: str = 'waiting' 10 | PAID: str = 'paid' 11 | CANCELLED: str = 'cancelled' 12 | 13 | @classmethod 14 | def has_value(cls, value): 15 | return value in cls._member_map_.values() 16 | 17 | 18 | class BuyerId(StrIdValueObject): 19 | value: Union[str, 'BuyerId'] 20 | 21 | 22 | class OrderItem(ValueObject): 23 | product_id: str 24 | amount: int 25 | 26 | @validator('amount', pre=False, check_fields=False) 27 | def validate_amount(cls, value): 28 | if value < 0: 29 | raise ValueError(f'Expected OrderAmount >= 0, got {value}') 30 | return value 31 | 32 | 33 | class OrderId(StrIdValueObject): 34 | value: Union[str, 'OrderId'] 35 | 36 | 37 | class OrderStatus(ValueObject): 38 | Enum = OrderStatusEnum 39 | status: str 40 | 41 | def __init__(self, status): 42 | super().__init__(status=status) 43 | 44 | def is_waiting(self) -> bool: 45 | return self.status == OrderStatus.Enum.WAITING 46 | 47 | def is_paid(self) -> bool: 48 | return self.status == OrderStatus.Enum.PAID 49 | 50 | def is_cancelled(self) -> bool: 51 | return self.status == OrderStatus.Enum.CANCELLED 52 | 53 | @validator('status', check_fields=False) 54 | def validate(cls, value): 55 | if not OrderStatusEnum.has_value(value): 56 | raise ValueError(f'OrderStatus named "{value}" not exists') 57 | return value 58 | -------------------------------------------------------------------------------- /src/domain/payment/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/payment/__init__.py -------------------------------------------------------------------------------- /src/domain/payment/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/payment/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/payment/adapters/paypal_adapter.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | 3 | from domain.payment.ports.payment_adapter_interface import PaymentAdapterInterface 4 | from domain.payment.value_objects import PaymentId 5 | 6 | 7 | class PayPalPaymentAdapter(PaymentAdapterInterface): 8 | async def new_payment(self, total_price: float) -> PaymentId: 9 | return PaymentId(str(uuid.uuid4())) 10 | 11 | async def verify_payment(self, payment_id: PaymentId) -> bool: 12 | return True 13 | -------------------------------------------------------------------------------- /src/domain/payment/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/payment/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/payment/ports/payment_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from domain.payment.value_objects import PaymentId 3 | 4 | 5 | class PaymentAdapterInterface(abc.ABC): 6 | @abc.abstractmethod 7 | async def new_payment(self, total_price: float) -> PaymentId: 8 | raise NotImplementedError 9 | 10 | @abc.abstractmethod 11 | async def verify_payment(self, payment_id: PaymentId) -> bool: 12 | raise NotImplementedError 13 | -------------------------------------------------------------------------------- /src/domain/payment/value_objects.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | from domain.base.value_object import StrIdValueObject 3 | 4 | 5 | class PaymentId(StrIdValueObject): 6 | value: Union[str, 'PaymentId'] 7 | -------------------------------------------------------------------------------- /src/domain/product/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/product/__init__.py -------------------------------------------------------------------------------- /src/domain/product/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/product/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/product/adapters/product_adapter.py: -------------------------------------------------------------------------------- 1 | from typing import List, Tuple 2 | 3 | from domain.product.value_objects import ProductId 4 | from domain.product.ports.product_adapter_interface import ProductAdapterInterface 5 | 6 | 7 | class ProductAdapter(ProductAdapterInterface): 8 | async def total_price(self, product_counts: List[Tuple[ProductId, int]]) -> float: 9 | price_list = [12.0 * count for product, count in product_counts] 10 | return float(sum(price_list)) 11 | -------------------------------------------------------------------------------- /src/domain/product/entities.py: -------------------------------------------------------------------------------- 1 | from domain.model.entity import Entity 2 | from domain.product.value_objects import ProductId 3 | 4 | 5 | class Product(Entity): 6 | product_id: ProductId 7 | price: float 8 | -------------------------------------------------------------------------------- /src/domain/product/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/src/domain/product/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/product/ports/product_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from typing import List, Tuple 3 | from domain.product.value_objects import ProductId 4 | 5 | 6 | class ProductAdapterInterface(abc.ABC): 7 | @abc.abstractmethod 8 | async def total_price(self, product_counts: List[Tuple[ProductId, int]]) -> float: 9 | raise NotImplementedError 10 | -------------------------------------------------------------------------------- /src/domain/product/value_objects.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | from domain.base.value_object import StrIdValueObject 3 | 4 | 5 | class ProductId(StrIdValueObject): 6 | id: Union[str, 'ProductId'] 7 | -------------------------------------------------------------------------------- /src/event_handler.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from database import get_mongo_db 3 | 4 | 5 | async def startup(app: FastAPI): 6 | app.state.event_source = get_mongo_db(app.state.event_source_config) 7 | 8 | 9 | async def shutdown(app: FastAPI): 10 | app.state.event_source.close() 11 | -------------------------------------------------------------------------------- /src/exceptions.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Union 2 | 3 | 4 | class CommonException(Exception): 5 | """Base exception class for all exceptions in this project.""" 6 | 7 | code: int = 400 8 | message: str 9 | detail: Union[Any, None] 10 | 11 | def __init__( 12 | self, code: int = 400, message: str = 'Bad Request', detail: Union[Any, None] = None 13 | ): 14 | self.code = code 15 | self.message = message 16 | self.detail = detail 17 | 18 | def __str__(self): 19 | return f''' 20 | code: {self.code} 21 | message: {self.message} 22 | detail: {self.detail} 23 | traceback: {self.__traceback__} 24 | ''' 25 | 26 | def to_dict(self): 27 | return { 28 | 'code': self.code, 29 | 'message': self.message, 30 | 'detail': self.detail, 31 | } 32 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | import uvicorn 2 | import settings 3 | from app import create_app 4 | 5 | app = create_app() 6 | 7 | app_base_configs = { 8 | 'host': '0.0.0.0', 9 | 'port': settings.PORT, 10 | 'workers': settings.UVICORN_WORKERS, 11 | 'access_log': True, 12 | } 13 | 14 | if __name__ == '__main__': 15 | uvicorn.run('main:app', **app_base_configs) 16 | -------------------------------------------------------------------------------- /src/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | 4 | class HealthCheck(BaseModel): 5 | status: int 6 | -------------------------------------------------------------------------------- /src/settings.py: -------------------------------------------------------------------------------- 1 | from decouple import config 2 | from pydantic import BaseSettings 3 | 4 | APPLICATION_NAME = config('APPLICATION_NAME', default='hexagonal-architecture-with-python') 5 | PORT = config('PORT', default=8090, cast=int) 6 | UVICORN_WORKERS = config('UVICORN_WORKERS', default=3, cast=int) 7 | 8 | 9 | class MongoDatabaseSettings(BaseSettings): 10 | MONGO_SERVER: str = 'mongo-db' 11 | MONGO_PORT: str = '27017' 12 | MONGO_USERNAME: str = '' 13 | MONGO_PASSWORD: str = '' 14 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/hexagonal-architecture-with-python/f7794ca24bbca61624729539aa3706c07ed4a3d8/tests/__init__.py --------------------------------------------------------------------------------