【发布时间】:2015-07-03 03:39:52
【问题描述】:
我有以下应用和测试:
app.py
from json import JSONEncoder
from flask import Flask, jsonify
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
return {"hello": "world"}
app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
@app.route('/')
def main():
return jsonify({'yep': 'this worked'})
if __name__ == '__main__':
app.run()
test_app.py
import json
from app import app
def test_this_should_work():
test_client = app.test_client()
rv = test_client.get('/')
assert json.loads(rv.data.decode()) == {'hello': 'world'}
据this example 所知,我的代码应该可以工作并返回这本其他字典。然而,事实并非如此。你可以通过python app.py 或py.test 运行它(如果你安装了py.test),你会发现两次都返回{"yep": "this worked"}。
这里出了点问题 - 我错过了什么?
【问题讨论】:
-
你有没有忘记在
CustomJSONEncoder末尾添加return JSONEncoder.default(self, {"hello": "world"})而不是{"hello": "world"}? -
为什么不只是猴子补丁
flask.json.jsonify?将JSONEncoder的默认值设置为您选择的函数。