summaryrefslogtreecommitdiff
path: root/day9/task5/main.py
blob: 795dc19ce5600dafca40d315827fc1de08e5ee72 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs
import re

import MySQLdb

from config import *


def render_template(path, **kwargs):
    with open(path) as f:
        template = f.read()

    for key in kwargs:
        template = template.replace(f'%%{key}%%', kwargs[key])

    return template


def parse_query(query):
    parsed_query = {'expression': {}, 'condition': {}}

    pattern = re.compile(r'(expression|condition)(\d+)_(key|value)')

    for key, (value,) in query.items():
        match = pattern.fullmatch(key)
        if match is not None:
            index = int(match.group(2))
            if index not in parsed_query[match.group(1)]:
                parsed_query[match.group(1)][index] = {}

            parsed_query[match.group(1)][index][match.group(3)] = value

    expressions = []
    for expression in parsed_query['expression'].values():
        expressions.append('`{}`="{}"'.format(
            expression['key'], expression['value']
        ))
    expressions = ','.join(expressions)

    conditions = []
    for condition in parsed_query['condition'].values():
        conditions.append('`{}`="{}"'.format(
            condition['key'], condition['value']
        ))
    conditions = ','.join(conditions)

    return {'expressions': expressions, 'conditions': conditions}


class MyHTTPRequestHandler(BaseHTTPRequestHandler):
    def update_post(self, query):
        expressions, conditions = parse_query(query)

        cursor = db.cursor()
        cursor.execute('UPDATE `table_task1` SET {} WHERE {}'.format(
            expressions, conditions
        ))
        result = cursor.fetchall()
        cursor.close()

        return f'<h1>UPDATE: {result}</h1>'

    def delete_post(self, query):
        return f'<h1>DELETE: {query}</h1>'

    def add_post(self, query):
        return f'<h1>ADD: {query}</h1>'

    def index_get(self):
        cursor = db.cursor()
        cursor.execute('DESCRIBE table_task1;')
        table_structure = cursor.fetchall()

        cursor.execute('SELECT * FROM table_task1;')
        content = cursor.fetchall()

        cursor.close()

        heading = []
        for column in [field[0] for field in table_structure]:
            heading.append(f'<th>{column}</th>')
        heading = '<thead><tr>\n%s\n</tr></thead>' % '\n'.join(heading)

        rows = []
        for row_index, row in enumerate(content):
            formatted = []
            for field_index, field in enumerate(row):
                color = 'odd' if (field_index % 2 + row_index % 2) % 2 == 0 else 'even'

                formatted.append(f'<td class={color}>{field}</td>')

            rows.append('<tr>{}</tr>'.format(''.join(formatted)))

        body = '<tbody>{}</tbody>'.format("\n".join(rows))

        data = render_template('index.html', heading=heading, body=body)

        return data

    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        if self.path == '/':
            response = self.index_get()
        else:
            response = '<center><h1>ERROR 404 NOT FOUND</h1></center>'

        self._set_response()
        self.wfile.write(response.encode('utf-8'))

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = parse_qs(self.rfile.read(content_length).decode('utf-8'))

        if self.path == '/update':
            response = self.update_post(post_data)

        elif self.path == '/delete':
            response = self.delete_post(post_data)

        elif self.path == '/add':
            response = self.add_post(post_data)

        else:
            response = '<center><h1>ERROR 404 NOT FOUND</h1></center>'

        self._set_response()
        self.wfile.write(response.encode('utf-8'))


# В файле config.py создайте соответствующие переменные
db = MySQLdb.connect(
    host=HOST,
    user=USERNAME,
    passwd=PASSWORD,
    db=DATABASE_NAME
)

db.cursor().execute(
    '''
    CREATE TABLE IF NOT EXISTS `table_task1` (
      `service_id` int(11) NOT NULL AUTO_INCREMENT,
      `servtype` varchar(20) NOT NULL DEFAULT 'hosting',
      `subtype` varchar(32) NOT NULL DEFAULT '',
      `user_id` bigint(20) NOT NULL,
      `referrer_user_id` bigint(20) NOT NULL,
      `state` varchar(1) NOT NULL DEFAULT 'N',
      `creation_date` date NOT NULL DEFAULT '0000-01-01',
      `creation_time` time NOT NULL DEFAULT '00:00:00',
      `creation_request_sent_date` datetime DEFAULT NULL,
      `notified_about_expiration` smallint(6) NOT NULL DEFAULT '0',
      PRIMARY KEY (`service_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=35109400 DEFAULT CHARSET=utf8;
    '''
)

server_address = ("", 8000)
httpd = HTTPServer(server_address, MyHTTPRequestHandler)
httpd.serve_forever()