Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

376
Visualizações
Flask - What is difference when returning jsonify vs dict?

I have route which returns response to the user on POST request. I am returning a dict on request. The problem is for some cases returning a dict works fine, but sometimes throws an error.

Can anyone please explain what is the ideal return type and why the dict return is successful for some of the cases ?

@app.route('/getuser', methods = ['post'] )
def getusername():
    user = request.json.get("user_name")

    # This works good for few cases
    return {"username": user}

    # Whereas other require this
    return jsonify({"username": user})
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

TLDR: There is no difference.


Basic example:

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/getuser_dict', methods=['POST'])
def getuser_dict():
    user = request.json.get("user_name")
    return {"username": user}


@app.route('/getuser_jsonify', methods=['POST'])
def getuser_jsonify():
    user = request.json.get("user_name")
    return jsonify({"username": user})


if __name__ == '__main__':
    app.run()

Sending POST request and retrieving response from both /getuser_dict and /getuser_jsonify are same (irrelevant parts left out):

> POST ...
> Host: 127.0.0.1:5000
> User-Agent: insomnia/7.0.3
> Content-Type: application/json
> Accept: */*
> Content-Length: 24

| {
|   "user_name": "John"
| }

* upload completely sent off: 24 out of 24 bytes
* HTTP 1.0, assume close after body

< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 20
< Server: Werkzeug/0.16.0 Python/3.6.8
< Date: Wed, 06 Nov 2019 09:34:51 GMT


* Received 20 B chunk
* Closing connection 65

Returning dict internally only checks what type of object are you returning, is it string, tuple, BaseResponse or dict. When it determines you really return dict by isinstance(rv, dict), it calls jsonify(rv) on your dict object and returns.

Please take a look at make_response method of app.py. The part where it checks is it a dict object is also there.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda