Flask-PyMongo - Object of type InsertOneResult is not JSON serializable

一世执手 提交于 2019-12-02 08:12:31
  1. from bson.objectid import ObjectId
  2. from bson import json_util

    • use pymongo json_util bson to handle BSON types
  3. use force=true when getting json input :

    • req = request.get_json(force=true)
  4. use default values when getting dict fields like :
    • req.get("email", "")

you can check if fields are empty or not before inserting into mongo.

Simple Solution I found from here is

TypeError: ObjectId('') is not JSON serializable

Response -> bson dumps (searlization) -> json loads (deserialization)

Code is as follows :

from bson.json_util import dumps,RELAXED_JSON_OPTIONS
import json


def post(self,name):
        dream = {'name':name , 'price' : 12.00 }
        dreams.append(dream)
        dreamDao.addDream(dream) #MongoDB Call to Insert Data 
        bs = dumps(dream,json_options=RELAXED_JSON_OPTIONS) #Now dream has Response Which will have ObjectId
        return json.loads(bs) , 201

The line TypeError: Object of type InsertOneResult is not JSON serializable describes the problem. insert_one() returns an InsertOneResult object, which contains the inserted ID (as @styvane's comment suggested) as well as a flag indicating whether the write was ack'd by the database. Other operations have similar result objects, and none of them are JSON serializable.

A future version of Flask-PyMongo may add helpers to support this, you can follow https://github.com/dcrosta/flask-pymongo/issues/62 to add ideas and suggestions.

from flask_pymongo import Pymongo
import json
import pandas as pd

user = pd.DataFrame(user)

mongo.db.users.insert_one({'email':json.loads(user[0].to_json(orient='index')),                            
                       'password':json.loads(user[1].to_json(orient='index'))})

This will throw up errors if your objects are already json. If they aren't though, it'll turn them into json and load them all in one go.

I believe that following previous suggestion you can find the answers. But I would like to provide another solution that simplifies it.

The solution assumes that pymongo and flask packages are installed:

from flask import Flask
from flask.json import JSONEncoder

from bson import json_util

from . import resources

# define a custom encoder point to the json_util provided by pymongo (or its dependency bson)
class CustomJSONEncoder(JSONEncoder):
    def default(self, obj): return json_util.default(obj)

application = Flask(__name__)
application.json_encoder = CustomJSONEncoder

if __name__ == "__main__":
    application.run()

It seems that what you post to server is not a valid json object. So you should debug what you got.

class UsersResource(Resource):

    def post(self):
        # debug
        print("request.args is {}".format(request.args))
        print("request.form is {}".format(request.form))
        print("request.data is {}".format(request.data))

        req = request.get_json()

        user = {
            "email": req.get("email"),
            "password": req.get("password")
        }

        result = mongo.db.users.insert_one(user)

        return jsonify(result)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!