【问题标题】:Why doesn't Flask use my custom json_encoder?为什么 Flask 不使用我的自定义 json_encoder?
【发布时间】: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.pypy.test 运行它(如果你安装了py.test),你会发现两次都返回{"yep": "this worked"}

这里出了点问题 - 我错过了什么?

【问题讨论】:

  • 你有没有忘记在CustomJSONEncoder 末尾添加return JSONEncoder.default(self, {"hello": "world"}) 而不是{"hello": "world"}
  • 为什么不只是猴子补丁flask.json.jsonify?将 JSONEncoder 的默认值设置为您选择的函数。

标签: python json flask


【解决方案1】:

这不是 Flask 的问题,which does send the custom encoder。这就是 Python 的 json 库的工作方式。 default 函数仅在无法识别被转储的对象时调用。由于您正在转储一个字符串,这是库识别的类型,因此它只是按原样转储。

如果要转换数据,请在序列化之前进行转换。


This recently came up on the Flask issue tracker as well.

【讨论】:

    猜你喜欢
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多