How to return multiple values in a python function?

Asked

Viewed 743 times

2

I am developing an API in Python FLASK and need to show the result of a SELECT that I made via SQL ALCHEMY. But when I use return he just comes back the first ROW of SELECT.

The funny thing is that with "print" it displays all results without any problem.

Could someone help me in this mystery?

def lista_unidades():
uni = session.query(UnidadesMam).all()
for u in uni:
    return json.dumps({'Unidade': u.nomeUni, 'Endereco': u.enderecoUni, 'Bairro': u.bairroUni, 'Cep': u.cepUni,
                        'Cidade': u.cidadeUni, 'Estado': u.estadoUni, 'Pais': u.paisUni})

1 answer

2


This is due to the return, that in the first loop is immediately invoked and the function where it is contained is terminated/terminated, in this case the lista_unidades(), do the following:

def lista_unidades():
    uni = session.query(UnidadesMam).all()
    dados = []
    for u in uni:
        dados.append({'Unidade': u.nomeUni, 'Endereco': u.enderecoUni, 'Bairro': u.bairroUni, 'Cep': u.cepUni, 'Cidade': u.cidadeUni, 'Estado': u.estadoUni, 'Pais': u.paisUni})
    return json.dumps(dados)
  • It worked well it returns all results inside the data array

  • Can we do without array rsrs ?

  • This I don’t know, maybe there is some flask functionality to do this directly @Yvesromeiro: http://stackoverflow.com/questions/7102754/jsonify-a-sqlalchemy-result-set-in-flask, http://code.runnable.com/UiIDW0LvVMFPAAAM/how-to-return-json-from-flask-for-python

Browser other questions tagged

You are not signed in. Login or sign up in order to post.