Getting 'TypeError: ObjectId('') is not JSON serializable' when using Flask 0.10.1

前端 未结 4 1509
时光取名叫无心
时光取名叫无心 2021-02-03 10:43

I forked the Flask example, Minitwit, to work with MongoDB and it was working fine on Flask 0.9, but after upgrading to 0.10.1 I get the error in title when I login when I try t

4条回答
  •  执念已碎
    2021-02-03 11:22

    JSON only supports serializing (encoding/decoding) a limited set of objects types by default. You could extend python JSON's decoder/encoder's to handle this situation though.

    In terms of encoding an object which contains on ObjectID, for example, when ObjectIds are created client side, which will be passed along to some awaiting server, try:

    import json
    from bson.objectid import ObjectId
    
    class Encoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, ObjectId):
                return str(obj)
            else:
                return obj
    

    Then, in your code, before pushing the data client -> server, run:

    json.dumps(obj, cls=Encoder)
    

    Server side, if we know we're dealing with mongo docs, (dictionary object with an '_id' key), we can define a json decoder hook like the following:

    def decoder(dct):
        for k, v in dct.items():
            if '_id' in dct:
                try:
                    dct['_id'] = ObjectId(dct['_id'])
                except:
                    pass
            return dct
    

    And call it using a call like the following:

    doc = json.loads(in_doc, object_hook=decoder)
    

    You'll probably need to adapt this code a bit, but for the simple case of passing

提交回复
热议问题