summaryrefslogtreecommitdiff
path: root/day9/task5/server.py
blob: c5178bd738b5086bada20bf500d53ba9ffa5ca26 (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 http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs
from json import dumps

from router import run
from utils import HTTP_STATUS_CODES, parse_multipart_form

import logging


class MyHTTPRequestHandler(BaseHTTPRequestHandler):
    def _set_response(self, code, content_type):
        self.send_response(code)
        self.send_header('Content-type', content_type)
        self.end_headers()

    def do_GET(self):
        try:
            content_length = int(self.headers['Content-Length'])
            get_data = parse_qs(self.rfile.read(content_length).decode('utf-8'))
        except TypeError:
            get_data = {}

        for key in get_data:
            get_data[key] = get_data[key][0]

        self.finalize_request(run({
            'url': self.path,
            'method': 'GET',
            'query': get_data
        }))

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        content_type = self.headers['Content-type']
        post_data = self.rfile.read(content_length)

        if content_type.split(';')[0] == 'multipart/form-data':
            files = parse_multipart_form(post_data)
            self.finalize_request(run({
                'url': self.path,
                'method': 'POST',
                'query': {'files': files}
            }))

        elif content_type.split(';')[0] == 'text/plain':
            post_data = parse_qs(post_data.decode('utf-8'))
            for key in post_data:
                post_data[key] = post_data[key][0]

            self.finalize_request(run({
                'url': self.path,
                'method': 'POST',
                'query': post_data
            }))

    def finalize_request(self, response):
        if isinstance(response, int):
            self._set_response(response, 'text/html')
            response = f'<center><h1>ERROR {response} {HTTP_STATUS_CODES[response].upper()}</h1></center>'.encode('utf-8')
        elif isinstance(response, (dict, list)):
            self._set_response(200, 'application/json')
            response = dumps(response).encode('utf-8')
        elif isinstance(response, tuple):
            if response[0] == 'image':
                self._set_response(200, f'image/{response[1]}')
                response = response[2]
            elif response[0] in ['css', 'js']:
                self._set_response(200, f'text/{response[1]}')
                response = response[2].encode('utf-8')
        else:
            self._set_response(200, 'text/html')
            response = response.encode('utf-8')

        self.wfile.write(response)


def start_server(host, port):
    server_address = (host, port)
    httpd = HTTPServer(server_address, MyHTTPRequestHandler)
    logging.getLogger('tableApp').info(f'Server started on {host}:{port}')
    httpd.serve_forever()