类型错误:Cursor 类型的对象不可 JSON 序列化

0 python api json mongodb flask

我正在创建一个太阳能系统应用程序,但遇到路由问题。我正在通过 Flask 并使用 mongodb 作为数据库创建这个应用程序。

我已确保插入 mongodb 的文件是 json 文件,但所有三个路由都收到相同的错误。我尝试过迭代每个集合中的每个文档,并且尝试过 json 转储。两者都不起作用。有任何想法吗?

应用程序.py

from flask import Flask, json, send_from_directory, request, jsonify
from flask.templating import render_template
from flask_restful import Api, Resource, reqparse
from flask_cors import CORS #comment this on deployment
from api.HelloApiHandler import HelloApiHandler
from  pymongo import MongoClient

app = Flask(__name__, static_url_path='', static_folder='Solar-System-Education\client\build')
CORS(app) #comment this on deployment
api = Api(app)

client = MongoClient("mongodb+srv://username:password@capstone.tbgw0.mongodb.net/Capstone?retryWrites=true&w=majority")
db = client.Capstone
planet_blurb = db.planet_descriptions
quiz_questions = db.quizzes
planet_stats = db.planets_info

@app.route("/Planets", methods = ['GET'])
def getplanetinfo():
    planets = (planet_stats.find())
    return jsonify(planets)

@app.route("/Quiz", methods = ["GET"])
def getquizquestions():
    quizzes = (quiz_questions.find())
    return jsonify(quizzes)

@app.route("/Planets", methods = ["GET"])
def getplanet_descriptions():
    descriptions = (planet_blurb.find())
    return jsonify(descriptions)



@app.route("/", defaults={'path':''})
def serve(path):
    return send_from_directory(app.static_folder,'index.html')

api.add_resource(HelloApiHandler, '/flask/hello')
Run Code Online (Sandbox Code Playgroud)

以防万一:HelloApiHandler.py

from flask_restful import Api, Resource, reqparse

class HelloApiHandler(Resource):
  def get(self):
    return {
      'resultStatus': 'SUCCESS',
      'message': "Hello Api Handler"
      }

  def post(self):
    print(self)
    parser = reqparse.RequestParser()
    parser.add_argument('type', type=str)
    parser.add_argument('message', type=str)

    args = parser.parse_args()

    print(args)
    # note, the post req from frontend needs to match the strings here (e.g. 'type and 'message')

    request_type = args['type']
    request_json = args['message']
    # ret_status, ret_msg = ReturnData(request_type, request_json)
    # currently just returning the req straight
    ret_status = request_type
    ret_msg = request_json

    if ret_msg:
      message = "Your Message Requested: {}".format(ret_msg)
    else:
      message = "No Msg"
    
    final_ret = {"status": "Success", "message": message}

    return final_ret
Run Code Online (Sandbox Code Playgroud)

根据要求提供完整的错误详细信息

Bel*_*ter 5

pymongo.find()返回一个游标对象,因此您会看到错误。您需要先将其转换为列表,然后再将其传递给jsonify(); 但要小心,如果返回的文档包含非标准类型(例如ObjectId),这会给出类似的错误。考虑使用bson.json_util.dumps()支持所有 MongoDB 类型的 json 序列化。

这将是对你所拥有的的改进:

@app.route("/Planets", methods = ['GET'])
def getplanetinfo():
    planets = planet_stats.find({}, {'_id': 0})
    return jsonify(list(planets))
Run Code Online (Sandbox Code Playgroud)