user6760639 user6760639 - 1 year ago 87
Python Question

How to collect a record by a parameter python

Python source :

@app.route('/pret/<int:idPret>', methods=['GET'])
def descrire_un_pret(idPret):

j = 0

for j in prets:
if prets[j]['id'] == idPret:
reponse = make_response(json.dumps(prets[j],200))
reponse.headers = {"Content-Type": "application/json"}
return reponse

I would like to retrieve a record in the
list by the
parameter. Nevertheless I get an error:

TypeError: list indices must be integers, not dict

Answer Source

j is not a number. j is one element in the prets list. Python loops are foreach loops. if j['id'] == idPret: would work:

for j in prets:
    if j['id'] == idPret:
        reponse = make_response(json.dumps(j, 200))
        reponse.headers = {"Content-Type": "application/json"}
        return reponse

I'd use a different name here, and use the flask.json.jsonify() function to create the response:

from flask import jsonify

for pret in prets:
    if pret['id'] == idPret:
        return jsonify(pret)

jsonify() takes care of converting to JSON and creating the response object with the right headers for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download