gpt4 book ai didi

python - MongoAlchemy 文档通过 Flask-MongoAlchemy 编码为 JSON

转载 作者:可可西里 更新时间:2023-11-01 09:58:26 35 4
gpt4 key购买 nike

我想我在这里遗漏了一些小东西。我正在测试 Python 框架 Flask 和 Flask-MongoAlchemy,并希望将实体转换为 JSON 输出。这是我的代码(抽象):

from flask import Flask
from flaskext.mongoalchemy import MongoAlchemy

try:
from bson.objectid import ObjectId
except:
pass

#a bunch of code to open the mongoDB

class ClassA(db.Document):
title = db.StringField()
field1 = db.StringField()
field2 = db.BoolField()

@app.route('/api/classA', methods=['GET'])
def api_list_all
a = ClassA.query.all()
result = []
for b in a:
result.append(b.wrap())
print result
return json.dumps(result)

如果没有 json.dumps 行,打印语句会提示正确的结果。但只有当我对结果运行 json.dumps 时,它才会产生:

TypeError: ObjectId('...') 不是 JSON 可序列化的

我错过了什么?

最佳答案

结果是某种包含 ObjectId 类型内容的 mongo 文档,您必须告诉 json 如何反序列化这些内容。对于其他特定于 mongo 的类型,例如 ReferenceField()、EmbeddedDocumentField() 等,您会遇到同样的问题。您必须编写一个可以传递给 json 的反序列化函数。我使用的是:

def encode_model(obj, recursive=False):
if obj is None:
return obj
if isinstance(obj, (mongoengine.Document, mongoengine.EmbeddedDocument)):
out = dict(obj._data)
for k,v in out.items():
if isinstance(v, ObjectId):
if k is None:
out['_id'] = str(v)
del(out[k])
else:
# Unlikely that we'll hit this since ObjectId is always NULL key
out[k] = str(v)
else:
out[k] = encode_model(v)
elif isinstance(obj, mongoengine.queryset.QuerySet):
out = encode_model(list(obj))
elif isinstance(obj, ModuleType):
out = None
elif isinstance(obj, groupby):
out = [ (g,list(l)) for g,l in obj ]
elif isinstance(obj, (list)):
out = [encode_model(item) for item in obj]
elif isinstance(obj, (dict)):
out = dict([(k,encode_model(v)) for (k,v) in obj.items()])
elif isinstance(obj, datetime.datetime):
out = str(obj)
elif isinstance(obj, ObjectId):
out = {'ObjectId':str(obj)}
elif isinstance(obj, (str, unicode)):
out = obj
elif isinstance(obj, float):
out = str(obj)
else:
raise TypeError, "Could not JSON-encode type '%s': %s" % (type(obj), str(obj))
return out

然后您将结果处理为:

return json.dumps(result, default=encode_model)

或类似的东西。

关于python - MongoAlchemy 文档通过 Flask-MongoAlchemy 编码为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7818956/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com