from bottle import route, run, static_file, template
import MySQLdb

HOST = 'localhost'

@route('/static/')
def server_static(filepath):
    return static_file(filepath, root='/home/mix/PycharmProjects/kea_for_miners/static/')

@route('/')
def server_homepage():
    dbhost = '10.5.1.248'
    dbuser = 'kea'
    dbpass = 'kea1234'
    dbbase = 'dhcp4'
    sql = "SELECT " \
          " expire, " \
          " INET_NTOA(address) as ip4, " \
          " HEX(hwaddr)as hw_addr, " \
          " hostname " \
          " FROM lease4 " \
          "where INET_NTOA(address) like '10.6.0%'" \
          " ORDER BY expire DESC;"
    try:
        conn = MySQLdb.connect(host=dbhost, user=dbuser,
                               passwd=dbpass, db=dbbase)
    except MySQLdb.Error as err:
        print("Connection error: {}".format(err))
        conn.close()
    try:
        cur = conn.cursor(MySQLdb.cursors.DictCursor)
        cur.execute(sql)
        data = cur.fetchall()
    except MySQLdb.Error as err:
        print("Query error: {}".format(err))
    conn.close()
    print(data)
    data_list = []
    for row in data:
        temp = []
        temp.append(row['expire'])
        temp.append(row['ip4'])
        temp.append(row['hw_addr'])
        temp.append(row['hostnamea'])
        data_list.append(temp)
    print(data_list)
    return template('main.tpl', A = data_list)

run(host=HOST, port=8080, debug=True)