diff options
Diffstat (limited to 'day9/task5/core.py')
| -rw-r--r-- | day9/task5/core.py | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/day9/task5/core.py b/day9/task5/core.py new file mode 100644 index 0000000..2bf9cf5 --- /dev/null +++ b/day9/task5/core.py @@ -0,0 +1,82 @@ +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'<center><h1>ERROR {http_code} {HTTP_STATUS_CODES[http_code].upper()}</h1></center><br>{message}' + super().__init__(html, http_code) |