summaryrefslogtreecommitdiff
path: root/day9/task5/core.py
diff options
context:
space:
mode:
authorAndrew <saintruler@gmail.com>2019-07-09 19:20:40 +0400
committerAndrew <saintruler@gmail.com>2019-07-09 19:20:40 +0400
commit3d7678361496668f584d62329600997dff9c2862 (patch)
treef73729667fdd306837c79520f193af384600df46 /day9/task5/core.py
parent323563cedae50dad25c531e90fcda17f9e459feb (diff)
Улучшена обработка разных видов ответов от бэкенда.
Diffstat (limited to 'day9/task5/core.py')
-rw-r--r--day9/task5/core.py82
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)