webservice changes

This commit is contained in:
2021-01-15 16:19:05 +01:00
parent 24482da680
commit e031660df9
3 changed files with 49 additions and 25 deletions

View File

@ -2,10 +2,6 @@ from dbpool import getConnection
from heroes_mock import HEROES
def get_heroes():
# if HEROES:
# return HEROES
# else:
# return 'No heroes available', 404
try:
dbh = getConnection()
heroes = []
@ -14,31 +10,49 @@ def get_heroes():
for (id, name) in cur:
heroes.append({"id": id, "name": name})
return heroes
except Exception:
return 500, str(Exception)
except Exception as err:
return str(err), 500
finally:
dbh.close()
def get_hero(id=None):
try:
hero = next(x for x in HEROES if x["id"] == id)
return { "id": hero["id"], "name": hero["name"] }
except StopIteration:
return 'Hero not found', 404
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:
heroToUpdate = next(x for x in HEROES if x["id"] == id)
checkNewName = next((x for x in HEROES if x["name"] == hero["name"]), None)
if (checkNewName):
return 'Duplicate name', 403
heroToUpdate["name"] = hero["name"]
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:
return 'Some error', 403
except Exception as err:
return str(err), 500
finally:
dbh.close()
def post_hero(hero=None):
try:
@ -46,5 +60,5 @@ def post_hero(hero=None):
hero["id"] = newHeroId
HEROES.append(hero)
return 'Hero inserted', 201
except Exception:
return 'Some error', 403
except Exception as err:
return str(err), 403