[英]How to return .find() as a response using Flask?
I'm learning Flask and I would like to append documents that I got from pymongo into ret and return 20 of those as a response.我正在学习 Flask,我想将从 pymongo 获得的 append 份文件放入 ret 中,并返回其中的 20 份作为响应。 I've found many solutions online but I couldn't found any.
我在网上找到了很多解决方案,但我找不到任何解决方案。 Thanks for your time.
谢谢你的时间。
This is the printed result:这是打印结果:
{'_id': ObjectId('5f6d8b87c8dcc2089446a153'), 'id': '5959764021', 'quiz1': 8, 'quiz2': 3, 'quiz3': 6, 'quiz4': 2, 'quiz5': 2, 'sum': 21} {'_id': ObjectId('5f6d8b87c8dcc2089446a153'), 'id': '5959764021', 'quiz1': 8, 'quiz2': 3, 'quiz3': 6, 'quiz4': 2, 'quiz5': 2, “总和”:21}
TypeError: Object of type 'ObjectId' is not JSON serializable类型错误:'ObjectId' 类型的 Object 不是 JSON 可序列化
@app.route('/get')
def findScore():
id_param= str(request.args.get('id'))
ret = dict()
cursor = db.scores.find({"id": { "$gt": id_param }}).sort("id",1).limit(20) #ascending
for document in cursor:
print(document)
ret = document
#print(str(ret))
return jsonify(ret)
app.run()
The issue is with the type()
of objectid
which is an instance.问题在于
objectid
的type()
是一个实例。
You can use json_utils to handle the BSON type before returning the value.您可以在返回值之前使用json_utils来处理 BSON 类型。
@app.route('/get')
def findScore():
id_param= str(request.args.get('id'))
ret = dict()
cursor = db.scores.find({"id": { "$gt": id_param }}).sort("id",1).limit(20) #ascending
for document in cursor:
print(document)
ret = document
return jsonify(json_utils.dumps(ret))
app.run()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.