看来这有效:
@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 模块。这样可以吗?
最佳答案
不,在 Flask 中返回字典不会自动应用 jsonify
。事实上,Flask 路由无法返回字典。
代码:
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.
屏幕截图:
由于回溯表明路由的返回类型必须是字符串、元组、响应实例或可调用的 WSGI。
关于python - 当你在flask中返回一个dict时,jsonify会自动应用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57470020/