Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Flask use my custom json_encoder?

Tags:

python

json

flask

I have the following application and test:

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'}   

As best as I can tell from this example, my code should work and return this other dictionary. However, it doesn't. You can run it via python app.py or py.test (if you install py.test), and you'll observe that both times return {"yep": "this worked"}.

Something is wrong here - what am I missing?

like image 816
Wayne Werner Avatar asked Apr 24 '15 13:04

Wayne Werner


1 Answers

This is not an issue with Flask, which does send the custom encoder. It's just the way Python's json library works. The default function is only called if the object being dumped is not recognized. Since you're dumping a string, which is a type recognized by the library, it's just dumped as is.

If you want to transform your data, do the transformation before serializing it.


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

like image 178
davidism Avatar answered Nov 07 '22 18:11

davidism