summaryrefslogtreecommitdiff
path: root/day9/task5/main.py
blob: 8ed3b50d499b2e4cd9a79063f1d7a548c3165ea1 (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
from router import route
from utils import render_template, parse_query
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('/')
def index_get(query, *args):
    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


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