当您在烧瓶中返回字典时,会自动应用jsonify吗?

时间:2019-08-13 01:20:02

标签: python json flask

似乎可行:

@app.route('/my/route/')
def my_route():
    return {
        'Something': True,
        'Else': None,
        'Thingy': 12345,
        'Blah': 'Blah'
    }

当我在浏览器中访问路线时,会得到如下有效的JSON:

{
    "Something": true, 
    "Else": null, 
    "Thingy": 12345
    "Blah": "Blah", 
}

所有内容都转换为有效的JSON,但是我还没有看到任何支持此内容的文档。我什至没有导入jsonify模块。可以吗?

2 个答案:

答案 0 :(得分:1)

否,在Flask中返回字典将不会自动应用jsonify。实际上,烧瓶路线无法返回字典。

代码:

from flask import Flask, render_template, json

app = Flask(__name__)

@app.route("/")
def index():
    return {
        'Something': True,
        'Else': None,
        'Thingy': 12345,
        'Blah': 'Blah'
    }

输出:

TypeError
TypeError: 'dict' object is not callable
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict.

屏幕截图:

showing error for returning dictionary

由于回溯表明路由的返回类型必须是字符串,元组,Response实例或WSGI可调用。

答案 1 :(得分:0)

定义自定义json编码器!会成功的!

import flask
import datetime

app = flask.Flask(__name__)

class CustomJSONEncoder(flask.json.JSONEncoder):
    def default(self, obj):
        if   isinstance(obj, datetime.date): return obj.isoformat()
        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return tuple(iterable)

        return flask.json.JSONEncoder.default(self, obj)

app.json_encoder = CustomJSONEncoder