栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在“编译”时不知道属性名称的情况下,使用Python复制Google App Engine数据存储区中的实体

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在“编译”时不知道属性名称的情况下,使用Python复制Google App Engine数据存储区中的实体

干得好:

def clone_entity(e, **extra_args):  """Clones an entity, adding or overriding constructor attributes.  The cloned entity will have exactly the same property values as the original  entity, except where overridden. By default it will have no parent entity or  key name, unless supplied.  Args:    e: The entity to clone    extra_args: Keyword arguments to override from the cloned entity and pass      to the constructor.  Returns:    A cloned, possibly modified, copy of entity e.  """  klass = e.__class__  props = dict((k, v.__get__(e, klass)) for k, v in klass.properties().iteritems())  props.update(extra_args)  return klass(**props)

用法示例:

b = clone_entity(a)c = clone_entity(a, key_name='foo')d = clone_entity(a, parent=a.key().parent())

编辑:如果使用NDB更改

将Gus的以下注释与对指定不同数据存储名称的属性的修复结合起来,以下代码可用于NDB:

def clone_entity(e, **extra_args):  klass = e.__class__  props = dict((v._pre_name, v.__get__(e, klass)) for v in klass._properties.itervalues() if type(v) is not ndb.ComputedProperty)  props.update(extra_args)  return klass(**props)

用法示例(注释在NDB中

key_name
变为
id
):

b = clone_entity(a, id='new_id_here')

旁注:请参阅的使用,

_pre_name
以获取Python友好的属性名称。如果没有此属性,则类似的属性
name =ndb.StringProperty('n')
将导致模型构造函数引发
AttributeError: type object 'foo' has noattribute 'n'



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516703.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号