从json模式动态创建mongoengine类 [英] creating mongoengine class dynamicly from json schema
问题描述
我正在寻找一种获取json模式并在运行时动态创建mongoengine类的方法.
i'm looking for a way to take my json schema and dynamically create a mongoengine class at runtime.
例如: 下面编写的mongoengine类
for example: the mongoengine class written below
class user(Document):
_id = StringField(required=False) # mongodb id
name = StringField(required=True) # user name
email= StringField(required=False,regex="^[a-zA-Z0-9]*@mydomain.com$") # user email
将与此模式下生成的在运行时动态生成的类相同
will be the same as the dynamically generated at runtime class generated from this schema
{
"type":"object",
"properties":{
"_id" : {"type":"string"},
"name" : {"type":"string"},
"email" : {"pattern":"^[a-zA-Z0-9]*@mydomain.com$"}
}
}
有什么建议吗?
推荐答案
您可以动态创建python类,如下所示:
You can create python classes dynamically, like below:
user_properties = {
'_id': StringField(required=False), # mongodb id
'name': StringField(required=True), # user name
'email': StringField(required=False,regex="^[a-zA-Z0-9]*@mydomain.com$"), # user email
}
User = type("User", (Document, ), user_properties)
其余的仅是来自具有您的模式"的字典的转换器.在输入中提供,将转换为字典user_properties
.
The remaining is only convertor from dict with "your schema" provided on input, that will be converted to dict user_properties
.
此外,这是对类似问题"我的答案 /a/63181047/3722635>如何从现有集合中为mongoengine文档生成模型"这也有帮助.
Also, here is my answer to similar question "How to generate a model for a mongoengine Document from an already existing collection" which can also help.
这篇关于从json模式动态创建mongoengine类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!