简体   繁体   English

Flask - 返回 jsonify 与 dict 有什么区别?

[英]Flask - What is difference when returning jsonify vs dict?

I have route which returns response to the user on POST request.我有路由可以在POST请求中向用户返回响应。 I am returning a dict on request.我正在应要求返回一个dict The problem is for some cases returning a dict works fine, but sometimes throws an error.问题是在某些情况下返回 dict 可以正常工作,但有时会引发错误。

Can anyone please explain what is the ideal return type and why the dict return is successful for some of the cases?谁能解释一下理想的返回类型是什么以及为什么某些情况下dict返回成功?

@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})

TLDR : There is no difference. TLDR没有区别。


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 ):/getuser_dict/getuser_jsonify发送POST请求和检索响应是相同的(不相关的部分省略):

> 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 .在内部返回dict仅检查您返回的是什么类型的 object,是stringtupleBaseResponse还是dict When it determines you really return dict by isinstance(rv, dict) , it calls jsonify(rv) on your dict object and returns.当它确定您确实通过isinstance(rv, dict)返回dict时,它会在您的dict object 上调用jsonify(rv)并返回。

Please take a look at make_response method of app.py .请看一下app.py 的 make_response app.py The part where it checks is it a dict object is also there.检查的部分是 dict object也在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM