我需要得到模型字段的列表,如:
@instance.register
class Todo(Document):
title = fields.StringField(required=True, default='Name')
description = fields.StringField()
created_at = fields.DateTimeField()
created_by = fields.StringField()
priority = fields.IntegerField()至
[
'title',
'description',
'created_at',
'created_by',
'priority'
]因此,我有返回字段列表的函数。
def get_class_properties(cls):
attributes = inspect.getmembers(cls, lambda a: not (inspect.isroutine(a)))
return [attr for attr in attributes if not (attr[0].startswith('__') and attr[0].endswith('__'))][1]但是用法给了我这个错误umongo.exceptions.NoDBDefinedError: init must be called to define a db
用法:properties=get_class_properties(Todo)
UPD这里是我的mongo初始化代码:
async def mongo_client(app):
conf = app["config"]["mongo"]
client = AsyncIOMotorClient(host=conf["host"], port=conf["port"])
db = client[conf["db"]]
instance.init(db)
await Todo.ensure_indexes()
app["db_client"]: AsyncIOMotorClient = client
app["db"] = db
yield
await app["db_client"].close()发布于 2019-08-02 18:09:48
诀窍是
properties=get_class_properties(Todo)
调用早于
async def mongo_client(app):
解决方案是按正确的顺序使用事物(参见代码注释)
async def init_app(argv=None):
app = web.Application(middlewares=[deserializer_middleware], logger=logger)
app["config"] = config
conf = app["config"]["mongo"]
client = AsyncIOMotorClient(host=conf["host"], port=conf["port"])
db = client[conf["db"]]
instance.init(db)
# Remove this line:
# app.cleanup_ctx.append(mongo_client)
app.cleanup_ctx.append(api_client)
register_routes(app)
return appdef register_routes(app: web.Application):
# Use here:
todo_resource = RestResource(
entity='todo',
factory=Todo,
properties=get_class_properties(Todo)
)
todo_resource.register(app.router)发布于 2019-07-26 14:11:18
据我所知,当您试图使用惰性客户端而没有正确初始化它们时,会引发此异常。uMongo的任何懒散类都希望在使用之前指定使用过的数据库。您需要的一切都是指定使用的数据库并调用懒惰实例的init方法,如下所示: 从motor.motor_asyncio导入AsyncIOMotorClient,从umongo导入MotorAsyncIOInstance client =MotorAsyncIOInstance client = client"test_database“lazy_umongo = MotorAsyncIOInstance() lazy_umongo.init(client) 例如,您可以查看Auth/Auth微服务代码,其中文档定义并存储在与实际使用不同的文件中。此外,这些以代码为例的文件(documents.py和mongodb.py)将帮助您找到解决方案。
https://stackoverflow.com/questions/57221730
复制相似问题