Files
hausverwaltung/tools/ws/heroes.py
2021-01-15 17:03:33 +01:00

64 lines
1.6 KiB
Python

from dbpool import getConnection
def get_heroes():
try:
dbh = getConnection()
heroes = []
cur = dbh.cursor()
cur.execute("SELECT id, name FROM hero")
for (id, name) in cur:
heroes.append({"id": id, "name": name})
return heroes
except Exception as err:
return str(err), 500
finally:
dbh.close()
def get_hero(id=None):
try:
dbh = getConnection()
cur = dbh.cursor()
cur.execute("SELECT id, name FROM hero WHERE id = ?", (id,))
hero = None
try:
(id, name) = cur.next()
hero = { "id": id, "name": name }
print("x1: {}\n".format(hero))
except StopIteration:
return "Hero not found", 404
try:
(id, name) = cur.next()
return "More than one hero by that id ({}, {})".format(id, name), 500
except:
pass
return hero
except Exception as err:
return str(err), 500
finally:
dbh.close()
def put_hero(id=None, hero=None):
try:
dbh = getConnection()
cur = dbh.cursor()
cur.execute("UPDATE hero SET name = ? WHERE id = ?", (hero["name"], id))
dbh.commit()
return 'Hero updated', 200
except StopIteration:
return 'Hero not found', 404
except Exception as err:
return str(err), 500
finally:
dbh.close()
def post_hero(hero=None):
try:
newHeroId = len(HEROES)
hero["id"] = newHeroId
HEROES.append(hero)
return 'Hero inserted', 201
except Exception as err:
return str(err), 403