From 048932c01b2c3031c6f8f3738ab9066c532c317b Mon Sep 17 00:00:00 2001 From: Andrew Date: Tue, 2 Jul 2019 19:43:15 +0400 Subject: =?UTF-8?q?WIP:=20=D0=A4=D1=80=D0=BE=D0=BD=D1=82=D0=B5=D0=BD=D0=B4?= =?UTF-8?q?,=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=20=D1=81=20=D0=B1?= =?UTF-8?q?=D0=B0=D0=B7=D0=B0=D0=BC=D0=B8=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day9/task5/index.html | 164 +++++++++++++++++++++++++++++++++++++++++++++++--- day9/task5/main.py | 137 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 286 insertions(+), 15 deletions(-) diff --git a/day9/task5/index.html b/day9/task5/index.html index 1785124..7d65bd9 100644 --- a/day9/task5/index.html +++ b/day9/task5/index.html @@ -1,9 +1,157 @@ - - - Python is awesome! - - -

Afternerd

-

Congratulations! The HTTP Server is working!

- + + + + + "table_task1" table view + + + + + + %%heading%% + + %%body%% +
+ +
+ `table_task1`
+ +
+
+ +
+
+ + + + \ No newline at end of file diff --git a/day9/task5/main.py b/day9/task5/main.py index 8cdf7a1..795dc19 100644 --- a/day9/task5/main.py +++ b/day9/task5/main.py @@ -1,13 +1,102 @@ from http.server import HTTPServer, BaseHTTPRequestHandler -import logging +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): - return f'

{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'

UPDATE: {result}

' + + def delete_post(self, query): + return f'

DELETE: {query}

' + + def add_post(self, query): + return f'

ADD: {query}

' def index_get(self): - return 'INDEX!!!!' + 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'{column}') + heading = '\n%s\n' % '\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'{field}') + + rows.append('{}'.format(''.join(formatted))) + + body = '{}'.format("\n".join(rows)) + + data = render_template('index.html', heading=heading, body=body) + + return data def _set_response(self): self.send_response(200) @@ -25,16 +114,50 @@ class MyHTTPRequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) - post_data = self.rfile.read(content_length).decode('utf-8') + 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) - response = self._router['POST'].get( - self.path, lambda *args: '

ERROR 404 NOT FOUND

' - )(post_data) + else: + response = '

ERROR 404 NOT FOUND

' 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() -- cgit v1.2.3