Pergunta

I have a python web service, which upon POST request creates new entry and assign it a new id as follows:

@app.route('/api/entries', methods = ['POST'])
def create_entry():
    if not request.json:
        abort(400)
    entry = {
        'id': entries[-1]['id'] + 1,
        'Name': request.json.get('Name', ""),
        'Surname': request.json.get('Surname', ""),
        'PhoneNb': request.json.get('PhoneNb', "")
    }
    entries.append(entry)
    return jsonify( { 'entry': entry } ), 201

The problem I have with this code though, is that if the entries array is empty, the

entries[-1]['id']

can not be evaluated and returns error:

IndexError: list index out of range

How can I work around it?

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top