【发布时间】:2013-08-11 12:57:00
【问题描述】:
我想就我正在尝试解决的一项小任务询问一些指导方针。 我正在试验一个使用 JSON 数据保存实体的小应用程序。
我知道您可以通过创建模型轻松地将 dict 转换为实体,但是,我正在尝试构建一种更通用的方法,将任何 dict 转换为实体。
我的步骤是:
- 获取字典。
- 通过读取模型的类dict来验证dict键是否对应于实体模型定义。
- 尝试在模型类构造器中解压已验证的属性(创建模型实例)
- 退货。
到目前为止,我还好,但缺乏我的 python 知识,要么限制我,要么让我困惑。 也许我也忘记或不知道更简单的方法。
就是这样:
@classmethod
def entity_from_dict(cls, parent_key, dict):
valid_properties = {}
logging.info(cls.__dict__)
for property,value in dict.iteritems():
if property in cls.__dict__: # should not iterate over functions, classmethods, and @property
logging.info(cls.__dict__[property]) # this outputs eg: StringProperty('title', required=True)
logging.info(type(cls.__dict__[property])) #this is more interesting <class 'google.appengine.ext.ndb.model.StringProperty'>
valid_properties.update({property: value})
# Update the id from the dict
if 'id' in dict: # if not creating a new entity
valid_properties['id'] = dict['id']
# Add the parent
valid_properties['parent'] = parent_key
#logging.info(valid_properties)
try:
entity = cls(**valid_properties)
except Exception as e:
logging.exception('Could not create entity \n' + repr(e))
return False
return entity
我的问题是我只想验证 ndb。属性而不是@classmethods,@property 也是如此,因为这会导致冲突。
我也在使用 expando 类,所以字典中任何额外的属性都会被存储。
如何检查这些特定类型?
【问题讨论】:
-
你为什么不使用 populate() 方法developers.google.com/appengine/docs/python/ndb/…。此外,一个实例列出了
_properties中的所有属性 -
@TimHoffman 我想我错过了。现在正在尝试。大概就是我需要的。谢谢,正如我所说,我知道我错过了一些东西。
-
@TimHoffman 我仍然存在的唯一问题是,因为我使用的是 expando 模型,所以额外的 dict 键值被写入数据存储区。如果字典中存在相同的键,则除了类方法和属性之外,还会创建一个 colsion
-
好的,这是您应该包含的一些信息。看看使用 _properties 来驱动属性迭代器而不是管道。
-
@TimHoffman 再次感谢。明白了,看答案
标签: python google-app-engine entity app-engine-ndb