Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions {{ cookiecutter.name }}/src/app/services.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
from abc import ABCMeta, abstractmethod
from collections.abc import Callable
from typing import Any


class BaseService(metaclass=ABCMeta):
class BaseService[T](metaclass=ABCMeta):
"""This is a template of a a base service.
All services in the app should follow this rules:
* Input variables should be done at the __init__ phase
* Service should implement a single entrypoint without arguments

This is ok:
@dataclass
class UserCreator(BaseService):
class UserCreator(BaseService[User]):
first_name: str
last_name: Optional[str]
last_name: str | None

def act(self) -> User:
return User.objects.create(first_name=self.first_name, last_name=self.last_name)
Expand All @@ -22,13 +21,13 @@ def act(self) -> User:

This is not ok:
class UserCreator:
def __call__(self, first_name: str, last_name: Optional[str]) -> User:
def __call__(self, first_name: str, last_name: str | None) -> User:
return User.objects.create(first_name=self.first_name, last_name=self.last_name)

For more implementation examples, check out https://github.com/tough-dev-school/education-backend/blob/master/src/apps/orders/services/order_course_changer.py
"""

def __call__(self) -> Any:
def __call__(self) -> T:
self.validate()
return self.act()

Expand All @@ -41,5 +40,4 @@ def validate(self) -> None:
validator()

@abstractmethod
def act(self) -> Any:
raise NotImplementedError("Please implement in the service class")
def act(self) -> T: ...