from abc import ABC, abstractmethod import json from utils import HTTP_STATUS_CODES class Response(ABC): @property def status_code(self) -> int: """ По дефолту возвращается статус 200 """ return 200 @property @abstractmethod def content_type(self) -> str: pass @property @abstractmethod def content(self) -> bytes: pass class HtmlResponse(Response): def __init__(self, html, status_code=200): self._html: str = html self._code = status_code @property def status_code(self) -> int: return self._code @property def content_type(self) -> str: return 'text/html' @property def content(self) -> bytes: return self._html.encode() class TextFileResponse(Response): def __init__(self, path, extension): with open(path, 'rb') as f: self._content = f.read() self._extension = extension @property def content_type(self) -> str: return f'text/{self._extension}' @property def content(self) -> bytes: return self._content class ImageResponse(TextFileResponse): @property def content_type(self) -> str: return f'image/{self._extension}' class JsonResponse(Response): def __init__(self, json_object): self._json_str = json.dumps(json_object, ensure_ascii=False) @property def content_type(self) -> str: return 'application/json' @property def content(self) -> bytes: return self._json_str.encode() class ErrorResponse(HtmlResponse): def __init__(self, http_code, message=''): html = f'

ERROR {http_code} {HTTP_STATUS_CODES[http_code].upper()}


{message}' super().__init__(html, http_code)