|
| 1 | +import logging |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import Protocol, Any |
| 4 | +from db import db_session, init_db, Article |
| 5 | + |
| 6 | +# ----------------------------------- |
| 7 | +# Protocols for loose coupling |
| 8 | +# ----------------------------------- |
| 9 | + |
| 10 | +class LoggerProtocol(Protocol): |
| 11 | + def info(self, msg: str, *args: Any, **kwargs: Any) -> None: ... |
| 12 | + def error(self, msg: str, *args: Any, **kwargs: Any) -> None: ... |
| 13 | + |
| 14 | +class DBProtocol(Protocol): |
| 15 | + def query(self, *args: Any, **kwargs: Any) -> Any: ... |
| 16 | + |
| 17 | +# ----------------------------------- |
| 18 | +# Context Object |
| 19 | +# ----------------------------------- |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class AppContext: |
| 23 | + user_id: int |
| 24 | + db: DBProtocol |
| 25 | + logger: LoggerProtocol |
| 26 | + config: dict[str, Any] |
| 27 | + |
| 28 | +# ----------------------------------- |
| 29 | +# Application Logic |
| 30 | +# ----------------------------------- |
| 31 | + |
| 32 | +def render_article(article_id: int, db: DBProtocol, logger: LoggerProtocol) -> str: |
| 33 | + article = db.query(Article).filter(Article.id == article_id).first() |
| 34 | + if not article: |
| 35 | + logger.error(f"Article {article_id} not found.") |
| 36 | + return "<p>Article not found.</p>" |
| 37 | + |
| 38 | + logger.info(f"Rendering article {article_id}") |
| 39 | + html = f"<h1>{article.title}</h1><p>{article.body}</p>" |
| 40 | + return html |
| 41 | + |
| 42 | +def send_to_external_service(html: str, api_key: str) -> None: |
| 43 | + print(f"Sending to API with key {api_key[:4]}... Content: {html[:30]}...") |
| 44 | + |
| 45 | +def publish_article(article_id: int, context: AppContext) -> None: |
| 46 | + html = render_article( |
| 47 | + article_id, |
| 48 | + db=context.db, |
| 49 | + logger=context.logger, |
| 50 | + ) |
| 51 | + send_to_external_service(html, context.config['api_key']) |
| 52 | + |
| 53 | +# ----------------------------------- |
| 54 | +# Entry Point |
| 55 | +# ----------------------------------- |
| 56 | + |
| 57 | +def main() -> None: |
| 58 | + logging.basicConfig(level=logging.INFO) |
| 59 | + logger = logging.getLogger("app") |
| 60 | + |
| 61 | + init_db() |
| 62 | + |
| 63 | + with db_session() as session: |
| 64 | + context = AppContext( |
| 65 | + user_id=42, |
| 66 | + db=session, |
| 67 | + logger=logger, |
| 68 | + config={"api_key": "abcdef123456"}, |
| 69 | + ) |
| 70 | + |
| 71 | + publish_article(1, context) |
| 72 | + publish_article(2, context) |
| 73 | + publish_article(999, context) # Not found example |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + main() |
| 77 | + |
| 78 | + |
0 commit comments