Use an exception handler to catch the IndexError
, and set a default id instead:
try:
entry_id = entries[-1]['id'] + 1
except IndexError:
entry_id = 1
entry = {
'id': entry_id,
'Name': request.json.get('Name', ""),
'Surname': request.json.get('Surname', ""),
'PhoneNb': request.json.get('PhoneNb', "")
}
entries.append(entry)
It's better use try
/except
here than to test for the length of entries
; you'll only have this issue once, after all.
Do know your code is not thread-safe nor will it work in a multiprocess WSGI container.