summaryrefslogtreecommitdiff
path: root/day9/task5/main.py
blob: db54d13c87f8f0d7863db1ed3c62623c7a123396 (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 router import route
from utils import render_template, parse_query, NOT_FOUND_CODE
from database import db
from config import SERVER_HOST, SERVER_PORT


@route('/update', ['POST'])
def update_post(query, *args):
    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>'


@route('/delete', ['POST'])
def delete_post(query, *args):
    return f'<h1>DELETE: {query}</h1>'


@route('/add', ['POST'])
def add_post(query, *args):
    return f'<h1>ADD: {query}</h1>'


@route('/get', ['POST'])
def db_get(query, *args):
    cursor = db.cursor()

    if query['type'] == 'full':
        cursor.execute('DESCRIBE table_task1;')
        table_structure = cursor.fetchall()

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

        cursor.close()

        table_headers = [field[0] for field in table_structure]

        json_content = []
        for row in content:
            new_row = []
            for col in row:
                if not isinstance(col, (float, bool, int, dict, list, tuple)):
                    col = str(col)
                new_row.append(col)
            json_content.append(new_row)

        return {'headers': table_headers, 'content': json_content}
    elif query['type'] == 'single_id':
        cursor.execute(f'SELECT * FROM table_task1 WHERE service_id="{query["service_id"]}";')
        content = cursor.fetchone()

        cursor.close()

        json_content = []
        for col in content:
            if not isinstance(col, (float, bool, int, dict, list, tuple)):
                col = str(col)
            json_content.append(col)

        return json_content

    return NOT_FOUND_CODE


@route('/')
def index_get(query, *args):
    data = render_template('index.html', heading=heading, body=body)

    return data


if __name__ == '__main__':
    from server import start_server
    start_server(SERVER_HOST, SERVER_PORT)