Created
August 17, 2022 17:15
-
-
Save akhundMurad/a7105d9ae5ed528e16be76eaee19fa71 to your computer and use it in GitHub Desktop.
Example of seperation of concepts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pymongo import MongoClient | |
| class BaseDAO: | |
| def create(self): | |
| ... | |
| def get(self): | |
| ... | |
| class MongoDAO(BaseDAO): | |
| def __init__(self): | |
| client = MongoClient("mongodb://localhost:21018") | |
| self.db = client.example | |
| def create(self, data: dict): | |
| self.db.posts.insert_one(data) | |
| def get(self): | |
| return list(self.db.posts.find({})) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing_extensions import Self | |
| from dataclasses import dataclass, field | |
| @dataclass | |
| class Post: | |
| title: str = field() | |
| data: str = field() | |
| @classmethod | |
| def from_dict(cls, data: dict) -> Self: | |
| return cls(title=data["title"], data=data["data"]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PostsLogic: | |
| def __init__(self, posts_collection: list[dict]) -> None: | |
| self.posts_collection = posts_collection | |
| def get_posts(self) -> list[dict]: | |
| posts: list[dict] = [] | |
| for post in self.posts_collection: | |
| post["data"] += f" {datetime.now()}" | |
| if datetime.now() > datetime(year=2022, month=8, day=17): | |
| post["outdated"] = True | |
| posts.append(post) | |
| return posts |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from logic import PostsLogic | |
| from dao import BaseDAO | |
| from dto import Post | |
| class Service: | |
| def __init__(self, dao: BaseDAO): | |
| self.dao = dao | |
| def get_posts_list(self) -> list[Post]: | |
| posts_collection = self.dao.get() | |
| logic = PostsLogic(posts_collection) | |
| posts = logic.get_posts() | |
| return Post.from_dict(posts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment