下载就不用我说啦:
pip install flask_mongoengine
一切按正常步骤做项目的时候,你一引入,你却发现!!这玩意居然报错!!!
于是我就以我原有的思维认为,这b肯定是我自己的代码写错了!!于是,开始了我那痛苦的一天,我代码一个一个排查,最后快崩溃的时候,上网查了一下,原因居然是:
from flask_mongoengine import MongoEngine
这句话和我们的flask版本不兼容,因为后续的维护者没有进行升级,导致一导入这句话就会报错!
然后我就想把flask的版本降低,但是想了想,不对呀,这样更加吃亏了呀,我很多插件是基于flask的2.3.2版本的呀,很难受那时候,然后吃了个饭,想了想,要不修改一下源代码?说干就干,开始了我一下午的网络查找答案的过程,最后还是靠chatgpt帮我修改了源代码,功夫不负有心人,最后成功解决!!!
源代码路径:
from bson import json_util
from json import JSONEncoder
from mongoengine.base import BaseDocument
from mongoengine.queryset import QuerySet
class MongoEngineJSONEncoder(JSONEncoder):
"""
A JSONEncoder which provides serialization of MongoEngine
documents and queryset objects.
"""
def default(self, obj):
if isinstance(obj, BaseDocument):
return json_util._json_convert(obj.to_mongo())
elif isinstance(obj, QuerySet):
return json_util._json_convert(obj.as_pymongo())
return super().default(obj)
def override_json_encoder(app):
"""
A function to dynamically create a new MongoEngineJSONEncoder class
based upon a custom base class.
This function allows us to combine MongoEngine serialization with
any changes to Flask's JSONEncoder which a user may have made
prior to calling init_app.
NOTE: This does not cover situations where users override
an instance's json_encoder after calling init_app.
"""
app.json_encoder = MongoEngineJSONEncoder
把源代码,换成我这个,你再次运行,发现一切都ok啦!!!!累死孩子了