【发布时间】:2019-12-04 21:33:51
【问题描述】:
我需要获取模型字段列表,例如:
@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()
【问题讨论】: