summaryrefslogtreecommitdiff
path: root/day9/task5/core.py
blob: 2bf9cf57fd12b5bbbcc55146fe29de414e8bfcb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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)